如何在UILabel中嵌入小图标

191

我需要将小图标(类似自定义符号)嵌入到我的 iOS7 的 UILabel 中。 在界面设计中,我该如何实现?或者至少在代码中怎么做呢?

在 Android 中,标签有左侧和右侧的 drawable 属性,但在 iOS 中该如何实现呢? Android 示例:

android sample


我不熟悉Android,你能发布一些图片作为参考吗? - user1673099
2
创建一个小的ImageView,并将其作为子视图添加到标签对象中。 - Saurabh Passolia
21个回答

314

你可以使用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;

1
@StevenJiang:你只需要在你的标签上添加一个UIImageView - Scott Berrevoets
1
很遗憾,这将图标放在文本之后。有没有可能把它移到文本之前呢?因为我找不到方法! - reVerse
4
与其将图像(附件字符串)添加到您的文本字符串中,你可以尝试相反的方法,即将文本字符串附加到附件字符串中。 - Scott Berrevoets
12
昨天已经尝试过了,似乎错过了什么,因为现在它运行正常。谢谢。以防万一,对于每个试图实现相同功能的人(因为它略有不同):NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString]; NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:text]; [myString appendAttributedString:myText]; - reVerse
但是图片显示在右侧...我需要将其保持在特定的位置...比如[图像可绘制左侧]。 - Yalamandarao
显示剩余7条评论

213

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

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


Swift 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;

输入图像描述

输入图像描述


32
附加.bounds的投票提升 - Peter Zhao
4
使用attachment.bounds是个好主意,正是我所需要的。 - Geoherna
5
实际上,可以通过计算imageOffsetY来代替使用固定值-5.0。请使用以下代码进行计算:let imageOffsetY: CGFloat = -(imageAttachment.image!.size.height - self.mobileLabel.font.pointSize) / 2.0; 注意不要改变原文的意思,并使翻译通俗易懂。 - JonSlowCN
1
注意:它会减慢编译时间。 - Jack
我可以在故事板上做吗? - Augusto
显示剩余2条评论

64

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

24

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
    }
}

23

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

enter image description here

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
这帮助我将我的奖杯图标放进了一个按钮中。非常感谢! - Harish

16

我已经在这里使用Swift实现了此功能: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 图片


15

Swift 5 轻松入门:只需复制粘贴并更改您想要的内容

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

输入图像描述


3
从2021年开始,你的屏幕发生了什么事;) - Zhou Haibo
2
这是我女朋友的礼物,她离开了我,但我怎么能扔掉这个礼物呢? :-( - Shakeel Ahmed
3
悲伤的故事。我认为你应该保留它。 - Zhou Haibo
2
从来没想过 Stack Overflow 会以这种方式让我感到沮丧。 - Alan S
1
@ShakeelAhmed 我来自未来,你现在还好吗?还是单身还是已婚了? - Tà Truhoada
@TàTruhoada 单身;-( 找个人给我看看 - Shakeel Ahmed

14

Swift 4 UIlabel扩展,可以在标签中添加图像,参考上面的答案。

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 是用来在图标和文本之间创建空间的吗? - Agent Smith
是的,还有其他方法可以在图标和文本之间添加空格吗? - Farzad

11
在Swift 5中,可以使用UILabel扩展在文本的前导和尾随位置嵌入图标,如下所示:
extension UILabel {
    
    func addTrailing(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let string = NSMutableAttributedString(string: text, attributes: [:])

        string.append(attachmentString)
        self.attributedText = string
    }
    
    func addLeading(image: UIImage, text:String) {
        let attachment = NSTextAttachment()
        attachment.image = image

        let attachmentString = NSAttributedString(attachment: attachment)
        let mutableAttributedString = NSMutableAttributedString()
        mutableAttributedString.append(attachmentString)
        
        let string = NSMutableAttributedString(string: text, attributes: [:])
        mutableAttributedString.append(string)
        self.attributedText = mutableAttributedString
    }
}

要在所需的标签中使用上述代码,方法如下:

文本右侧的图像:-

statusLabel.addTrailing(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

图像在文本左侧,然后:

statusLabel.addLeading(image: UIImage(named: "rightTick") ?? UIImage(), text: " Verified ")

输出:

输入图片描述

输入图片描述


5

试试这种方法...

  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
这种方法忽略了图像的文本偏移(文本位于图像后面)。 - brigadir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接