如何在UILabel中嵌入小图标

时间:2013-10-11 12:41:15

标签: ios objective-c cocoa-touch ios7 textkit

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

在Android中,标签有leftDrawablerightDrawable,但是如何在iOS中完成? android中的示例:

android sample

18 个答案:

答案 0 :(得分:278)

您可以使用iOS 7的text attachments执行此操作,这是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 :(得分:107)

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

同样对齐图标使用 attachment.bounds

Swift 4.2

//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 = NSMutableAttributedString(string: "Using attachment.bounds!")
completeText.append(textAfterIcon)
self.mobileLabel.textAlignment = .center;
self.mobileLabel.attributedText = completeText;

Objective-C Version

 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];
NSMutableAttributedString *textAfterIcon= [[NSMutableAttributedString alloc] initWithString:@"Using attachment.bounds!"];
[completeText appendAttributedString:textAfterIcon];
self.mobileLabel.textAlignment=NSTextAlignmentRight;
self.mobileLabel.attributedText=completeText;

enter image description here

enter image description here

答案 2 :(得分:47)

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

答案 3 :(得分:21)

您的参考图像看起来像一个按钮。尝试(也可以在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];

答案 4 :(得分:18)

Swift 3版本

import Vue from 'vue'

new Vue({
    el: '#app',
    data: {
        info: { email: '' },
        email: ''
    },

    methods: {

        onSignin: function (e) { },
    }
})

答案 5 :(得分:17)

我已在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 image

答案 6 :(得分:6)

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

答案 7 :(得分: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

答案 8 :(得分:3)

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

答案 9 :(得分: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];

答案 10 :(得分: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
    }

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

谢谢。

答案 11 :(得分:1)

在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 ")

输出:-

enter image description here

enter image description here

答案 12 :(得分: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
} 

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

答案 13 :(得分: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
    }
}

答案 14 :(得分:1)

您可以将UITextFieldleftView属性一起使用,然后将enabled属性设置为NO

或使用UIButtonsetImage:forControlState

答案 15 :(得分:0)

您必须在使用UIView的位置制作自定义对象,并在其中放置UIImageViewUILabel

答案 16 :(得分:0)

快速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

enter image description here

答案 17 :(得分:0)

如果需要,您可以扩展 UILabe 传递图像加载项的标志为 Lead 或 Trailing,还可以设置 imageBounds。

Swift 5+

extension UILabel {
    func add(image: UIImage, text: String, isLeading: Bool = true, imageBounds: CGRect = CGRect(x: 0, y: 0, width: 16, height: 12)) {
        let imageAttachment = NSTextAttachment()
        imageAttachment.bounds = imageBounds
        
        imageAttachment.image = image
        
        let attachmentString = NSAttributedString(attachment: imageAttachment)
        let string = NSMutableAttributedString(string: text)
        
        let mutableAttributedString = NSMutableAttributedString()
        
        if isLeading {
            mutableAttributedString.append(attachmentString)
            mutableAttributedString.append(string)
            attributedText = mutableAttributedString
        } else {
            string.append(attachmentString)
            attributedText = string
        }
    }
    }