如何添加文本背景标签部分的图像?

How to add a image of a Label's part of text background?

下面是添加属性字符串背景颜色的示例代码,但我想为图像设置标签属性字符串颜色。有什么办法吗?

let attributedString = NSMutableAttributedString(string:text!)
        attributedString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.red , range: range)

您想获取标签的属性文本并将背景颜色应用于 UIImageView

您可以通过 label.attributedText 获取应用于标签的属性文本,然后您可以获得 NSBackgroundColorAttributeName 并应用于您的 ImageView

UIColor 有一个名为 "patternImage" 的方法,我们可以在其中设置图像

 let attributedString = NSMutableAttributedString(string:text!)
           attributedString.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor(patternImage: UIImage(named: "bg.png")!) , range: range)
           label.attributedText = attributedString

您可以简单地使用 textColor 属性 of UILabel

label.textColor = UIColor(patternImage: UIImage(named:"Pattern.jpg")!)