如何在UILabel中嵌入小图标


152

我需要UILabel在iOS7中嵌入一​​些小图标(某种自定义项目符号)。如何在界面设计器中执行此操作?或至少在代码中?

在Android中有leftDrawablerightDrawable用于标签,但是在iOS中如何实现?android中的示例:

android示例


我不熟悉Android,您可以发布一些图片以供参考吗?
user1673099 2013年

2
创建一个小的imageview并将其作为子视图添加到标签的对象
Saurabh Passolia

Answers:


292

您可以使用iOS 7的文本附件(属于TextKit的一部分)来执行此操作。一些示例代码:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];

myLabel.attributedText = myString;

iOS6怎么样?你有什么建议吗?Thx
史蒂芬·姜

1
@StevenJiang:您只需UIImageView在标签上添加一个即可
Scott Berrevoets 2014年

1
不幸的是,这会将图标放在文本后面。因为找不到方法,我们是否有可能将其移至文本之前?
2014年

4
@reVerse可以将图像字符串附加到附件字符串,而不是将图像(附件字符串)附加到文本字符串,而可以尝试使用另一种方法。
Scott Berrevoets 2014年

11
昨天已经尝试过了。似乎错过了一些东西,因为现在可以使用了。谢谢。以防万一,每个尝试实现相同目标的人(因为它略有不同): NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString]; NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:text]; [myString appendAttributedString:myText];
reVerse 2014年

153

这是在UILabel中嵌入图标的方法。

另外要对齐图标,请使用attachment.bounds


迅捷5.1

// Create Attachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named:"iPhoneIcon")
// Set bound to reposition
let imageOffsetY: CGFloat = -5.0
imageAttachment.bounds = CGRect(x: 0, y: imageOffsetY, width: imageAttachment.image!.size.width, height: imageAttachment.image!.size.height)
// Create string with attachment
let attachmentString = NSAttributedString(attachment: imageAttachment)
// Initialize mutable string
let completeText = NSMutableAttributedString(string: "")
// Add image to mutable string
completeText.append(attachmentString)
// Add your text to mutable string
let textAfterIcon = NSAttributedString(string: "Using attachment.bounds!")
completeText.append(textAfterIcon)
self.mobileLabel.textAlignment = .center
self.mobileLabel.attributedText = completeText

Objective-C版本

NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
imageAttachment.image = [UIImage imageNamed:@"iPhoneIcon"];
CGFloat imageOffsetY = -5.0;
imageAttachment.bounds = CGRectMake(0, imageOffsetY, imageAttachment.image.size.width, imageAttachment.image.size.height);
NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:imageAttachment];
NSMutableAttributedString *completeText = [[NSMutableAttributedString alloc] initWithString:@""];
[completeText appendAttributedString:attachmentString];
NSAttributedString *textAfterIcon = [[NSAttributedString alloc] initWithString:@"Using attachment.bounds!"];
[completeText appendAttributedString:textAfterIcon];
self.mobileLabel.textAlignment = NSTextAlignmentRight;
self.mobileLabel.attributedText = completeText;

在此处输入图片说明

在此处输入图片说明


22
投票给attachment.bounds
彼得·赵

3
伟大的呼吁使用attachment.bounds。那正是我想要的。
Geoherna

2
实际上,可以计算imageOffsetY而不是使用-5.0的固定值。让imageOffsetY:CGFloat =-(imageAttachment.image!.size.height-self.mobileLabel.font.pointSize)/ 2.0;
JonSlowCN

注意:它会减慢编译时间
杰克

我可以在情节提要上做到吗?
奥古斯托

53

Swift 4.2:

let attachment = NSTextAttachment()        
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.append(attachmentString)
label.attributedText = myString

23

您的参考图像看起来像一个按钮。尝试(也可以在Interface Builder中完成):

在此处输入图片说明

UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(50, 50, 100, 44)];
[button setImage:[UIImage imageNamed:@"img"] forState:UIControlStateNormal];
[button setImageEdgeInsets:UIEdgeInsetsMake(0, -30, 0, 0)];
[button setTitle:@"Abc" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setBackgroundColor:[UIColor yellowColor]];
[view addSubview:button];

很好的解释,我喜欢您花时间提供参考的事实。这对我帮助很大!谢谢
Shinnyx 2014年

这有助于将我的奖杯图标变成按钮。非常感谢!
Harish

23

Swift 3版本

let attachment = NSTextAttachment()
attachment.image = UIImage(named: "plus")
attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
let attachmentStr = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: "")
myString.append(attachmentStr)
let myString1 = NSMutableAttributedString(string: "My label text")
myString.append(myString1)
lbl.attributedText = myString

UILabel扩展

extension UILabel {

    func set(text:String, leftIcon: UIImage? = nil, rightIcon: UIImage? = nil) {

        let leftAttachment = NSTextAttachment()
        leftAttachment.image = leftIcon
        leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: 20, height: 20)
        if let leftIcon = leftIcon {
            leftAttachment.bounds = CGRect(x: 0, y: -2.5, width: leftIcon.size.width, height: leftIcon.size.height)
        }
        let leftAttachmentStr = NSAttributedString(attachment: leftAttachment)

        let myString = NSMutableAttributedString(string: "")

        let rightAttachment = NSTextAttachment()
        rightAttachment.image = rightIcon
        rightAttachment.bounds = CGRect(x: 0, y: -5, width: 20, height: 20)
        let rightAttachmentStr = NSAttributedString(attachment: rightAttachment)


        if semanticContentAttribute == .forceRightToLeft {
            if rightIcon != nil {
                myString.append(rightAttachmentStr)
                myString.append(NSAttributedString(string: " "))
            }
            myString.append(NSAttributedString(string: text))
            if leftIcon != nil {
                myString.append(NSAttributedString(string: " "))
                myString.append(leftAttachmentStr)
            }
        } else {
            if leftIcon != nil {
                myString.append(leftAttachmentStr)
                myString.append(NSAttributedString(string: " "))
            }
            myString.append(NSAttributedString(string: text))
            if rightIcon != nil {
                myString.append(NSAttributedString(string: " "))
                myString.append(rightAttachmentStr)
            }
        }
        attributedText = myString
    }
}

17

我已经在这里快速实现了此功能:https : //github.com/anatoliyv/SMIconLabel

代码尽可能简单:

var labelLeft = SMIconLabel(frame: CGRectMake(10, 10, view.frame.size.width - 20, 20))
labelLeft.text = "Icon on the left, text on the left"

// Here is the magic
labelLeft.icon = UIImage(named: "Bell") // Set icon image
labelLeft.iconPadding = 5               // Set padding between icon and label
labelLeft.numberOfLines = 0             // Required
labelLeft.iconPosition = SMIconLabelPosition.Left // Icon position
view.addSubview(labelLeft)

外观如下:

SMIconLabel图片


12

Swift 4 UIlabel Extension参考以上答案将图像添加到标签

extension UILabel {
  func set(image: UIImage, with text: String) {
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(x: 0, y: 0, width: 10, height: 10)
    let attachmentStr = NSAttributedString(attachment: attachment)

    let mutableAttributedString = NSMutableAttributedString()
    mutableAttributedString.append(attachmentStr)

    let textString = NSAttributedString(string: text, attributes: [.font: self.font])
    mutableAttributedString.append(textString)

    self.attributedText = mutableAttributedString
  }
}

NSAttributedString(string: " " + text, attributes: [.font: self.font])
Farzad

@grizzly是用于在图标和文本之间创建空间的吗?
史密斯探员

是。图标和文本之间的另一种方式是空格?
Farzad

4

Swift 2.0版本:

//Get image and set it's size
let image = UIImage(named: "imageNameWithHeart")
let newSize = CGSize(width: 10, height: 10)

//Resize image
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let imageResized = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

//Create attachment text with image
var attachment = NSTextAttachment()
attachment.image = imageResized
var attachmentString = NSAttributedString(attachment: attachment)
var myString = NSMutableAttributedString(string: "I love swift ")
myString.appendAttributedString(attachmentString)
myLabel.attributedText = myString

3

尝试将a拖动UIView到IB的屏幕上。从那里,您可以将UIImageView和拖到UILabel刚创建的视图中。UIImageView在属性检查器中将的图像设置为自定义项目符号图像(必须将其拖动到导航窗格中才能添加到项目中),然后可以在标签中写入一些文本。


2

尝试这种方式...

  self.lbl.text=@"Drawble Left";
    UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    img.image=[UIImage imageNamed:@"Star.png"];
    [self.lbl addSubview:img];

这对您有帮助吗?
user1673099 2013年

这种方法会丢失图像的文本偏移(文本位于图像后面)
brigadir 2014年

2

Swift 5 Easy Way Just CopyPaste并更改您想要的内容

let fullString = NSMutableAttributedString(string:"To start messaging contacts who have Talklo, tap ")

 // create our NSTextAttachment
let image1Attachment = NSTextAttachment() 
image1Attachment.image = UIImage(named: "chatEmoji")
image1Attachment.bounds = CGRect(x: 0, y: -8, width: 25, height: 25)

// wrap the attachment in its own attributed string so we can append it
let image1String = NSAttributedString(attachment: image1Attachment)

 // add the NSTextAttachment wrapper to our full string, then add some more text.

 fullString.append(image1String)
 fullString.append(NSAttributedString(string:" at the right bottom of your screen"))

 // draw the result in a label
 self.lblsearching.attributedText = fullString

在此处输入图片说明



1

在Swift 2.0中,

我对这个问题的解决方案是这个问题的几个答案的组合。我在@Phil的答案中遇到的问题是我无法更改图标的位置,并且它始终出现在右上角。来自@anatoliy_v的一个答案是,我无法调整要附加到字符串的图标大小。

为了使它对我pod 'SMIconLabel'有用,我首先做了一个,然后创建了这个函数:

func drawTextWithIcon(labelName: SMIconLabel, imageName: String, labelText: String!,  width: Int, height: Int) {

        let newSize = CGSize(width: width, height: height)
        let image = UIImage(named: imageName)
        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        image?.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
        let imageResized = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        labelName.text = " \(labelText)"
        labelName.icon = imageResized
        labelName.iconPosition = .Left
    }

该解决方案不仅可以帮助您放置图像,还可以使您对图标大小和其他属性进行必要的更改。

谢谢。


1

Swift 3 UILabel扩展

提示:如果需要在图像和文本之间留一些空间,则只需在labelText之前使用一两个空间。

extension UILabel {
    func addIconToLabel(imageName: String, labelText: String, bounds_x: Double, bounds_y: Double, boundsWidth: Double, boundsHeight: Double) {
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: imageName)
        attachment.bounds = CGRect(x: bounds_x, y: bounds_y, width: boundsWidth, height: boundsHeight)
        let attachmentStr = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: "")
        string.append(attachmentStr)
        let string2 = NSMutableAttributedString(string: labelText)
        string.append(string2)
        self.attributedText = string
    }
}

1
我使用了它,并且效果很好。上面的其他内容实际上将图像翻转到字符串的末尾。
mondousage

1
 func atributedLabel(str: String, img: UIImage)->NSMutableAttributedString
{   let iconsSize = CGRect(x: 0, y: -2, width: 16, height: 16)
    let attributedString = NSMutableAttributedString()
    let attachment = NSTextAttachment()
    attachment.image = img
    attachment.bounds = iconsSize
    attributedString.append(NSAttributedString(attachment: attachment))
    attributedString.append(NSAttributedString(string: str))

    return attributedString
} 

您可以使用此功能向标签添加图像或小图标


在viewdidload()中调用它
Ayush Dixit

让emojisCollection = [UIImage(名称:“ ic_place”),UIImage(名称:“ ic_group”),UIImage(名称:“ ic_analytics”)] lbl1.attributedText = atributedLabel(str:“ Howath,Dublin”,img:emojisCollection [0 ]!)lbl2.attributedText = atributedLabel(str:“难度:18+”,img:emojisCollection [2]!)lbl3.attributedText = atributedLabel(str:“最大组大小:10”,img:emojisCollection [1]!)
Ayush Dixit

您可以编辑原始答案以包含上面的那些评论。
Moondra

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.