【问题标题】:How to embed small icon in UILabel如何在 UILabel 中嵌入小图标
【发布时间】:2013-10-19 13:12:35
【问题描述】:

我需要在 iOS7 中将小图标(某种自定义项目符号)嵌入到我的UILabel。 我如何在界面设计器中做到这一点?或者至少在代码中?

在 Android 中,标签有 leftDrawablerightDrawable,但在 iOS 中是如何实现的呢? 安卓示例:

【问题讨论】:

  • 我不熟悉Android,您可以发布一些图片以供参考吗?
  • 创建一个小图像视图并将其作为子视图添加到标签对象

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


【解决方案1】:

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

【讨论】:

  • iOS6怎么样?你有什么建议吗??谢谢
  • @StevenJiang:你只需要在你的标签上添加一个UIImageView
  • 不幸的是,这会将图标放在文本之后。有没有可能因为我找不到方法而把它移到正文之前?!
  • @reVerse 不要将图像(附件字符串)附加到您的文本字符串,您可以尝试反过来,将文本字符串附加到附件字符串。
  • 昨天已经试过了。似乎错过了一些东西,因为现在它可以工作了。谢谢。以防万一每个人都试图完成同样的事情(因为它略有不同):NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment]; NSMutableAttributedString *myString = [[NSMutableAttributedString alloc] initWithAttributedString:attachmentString]; NSAttributedString *myText = [[NSMutableAttributedString alloc] initWithString:text]; [myString appendAttributedString:myText];
【解决方案2】:

这是在 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;

【讨论】:

  • 为attachment.bounds投票
  • 很好地呼吁使用 attachment.bounds。这正是我想要的。
  • 其实可以计算imageOffsetY,而不是使用固定值-5.0。让 imageOffsetY:CGFloat = -(imageAttachment.image!.size.height - self.mobileLabel.font.pointSize) / 2.0;
  • 注意:它会减慢编译时间
  • 我可以在故事板上做吗?
【解决方案3】:

斯威夫特 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

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

      • 很好解释,我喜欢你花时间提供参考的事实。这对我帮助很大!谢谢
      • 这有助于将我的奖杯图标变成一个按钮。非常感谢!
      【解决方案6】:

      我在这里快速实现了这个功能: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)
      

      这是它的外观:

      【讨论】:

        【解决方案7】:

        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])
        • @grizzly 是用来在图标和文本之间创建空间的吗?
        • 是的。是另一种在图标和文本之间留出空间的方式吗?
        【解决方案8】:

        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
        

        【讨论】:

        • 从 2021 年开始,你的屏幕发生了什么变化;)
        • 它是我女朋友的礼物,她离开了我,但我怎么能把礼物扔掉呢? :-(
        • 悲伤的故事。我认为你应该保留它。
        【解决方案9】:

        试试这个方法...

          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】:

        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
        

        【讨论】:

          【解决方案11】:

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

          【讨论】:

            【解决方案12】:

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

            输出:-

            【讨论】:

              【解决方案13】:

              如果需要,您可以扩展 UILbe 传递图像加载项的标志Leading 或 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
                      }
                  }
                  }
              

              【讨论】:

                【解决方案14】:

                您必须在使用 UIView 的地方创建一个自定义对象,并在其中放置一个 UIImageView 和一个 UILabel

                【讨论】:

                  【解决方案15】:

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

                  或者使用UIButtonsetImage:forControlState

                  【讨论】:

                    【解决方案16】:
                     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() 中调用这个
                    • 让 emojisCollection = [UIImage(named: "ic_place"), UIImage(named: "ic_group"), UIImage(named: "ic_analytics")] lbl1.attributedText = atributedLabel(str: " Howath,都柏林”,img:emojisCollection[0]!)lbl2.attributedText = atributedLabel(str:“难度:18+”,img:emojisCollection[2]!)lbl3.attributedText = atributedLabel(str:“最大组大小:10”, img: emojisCollection[1]!)
                    • 您可以编辑您的原始答案以包括上面的那些 cmets。
                    【解决方案17】:

                    对于希望在标签右端有一个图标的人,不一定紧跟在文本之后,您可以根据此答案中的想法使用此技术:https://stackoverflow.com/a/19318843/826946 (请注意,这里有一些常量您可能需要调整,但总体思路应该很清楚)。如果您的标签使用其隐式大小调整大小,则这将不起作用,只有当您对宽度有一些其他限制并且您确信会为您的图标留出空间时。

                        let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
                        imgView.image = UIImage(named: "arrow")
                        myLabel.addSubview(imgView)
                        imgView.translatesAutoresizingMaskIntoConstraints = false
                        imgView.centerYAnchor.constraint(equalTo: myLabel.centerYAnchor, constant: 0).isActive = true
                        imgView.rightAnchor.constraint(equalTo: myLabel.rightAnchor, constant: -20).isActive = true
                    

                    【讨论】:

                      【解决方案18】:

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

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

                      谢谢。

                      【讨论】:

                        【解决方案19】:

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

                        【讨论】:

                        • 我用过这个,效果很好。上面的其他实际上将图像翻转到字符串的末尾。
                        猜你喜欢
                        • 1970-01-01
                        • 2023-03-05
                        • 1970-01-01
                        • 2018-10-15
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2013-07-01
                        相关资源
                        最近更新 更多