【问题标题】:How to add a image of a Label's part of text background?如何添加文本背景标签部分的图像?
【发布时间】:2018-09-22 11:08:16
【问题描述】:

以下是添加属性字符串背景颜色的示例代码,但我想为图像设置标签属性字符串颜色。有没有办法做到这一点?

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

【问题讨论】:

  • 你想给 UIImage 添加背景颜色,你可以使用 UIImageView.background color 属性
  • 您的描述不清楚。你想给图像着色吗?
  • @ReinierMelian:您好,我想添加标签特定文本的背景图片
  • 您的问题仍然模棱两可。我的理解是您想使用图像作为文本的背景(此文本在标签中)。对吗?

标签: ios swift swift3 swift4 nsattributedstring


【解决方案1】:

您可以简单地使用UILabeltextColor 属性

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 能否分享一些示例代码以供参考,因为我是 swift 新手
      • @MaheshPrasadMahalik 你应该自己尝试一下,你可以打印label.attributedText,在那里你可以看到所有应用于标签的属性。接下来你需要从中获取NSBackgroundColorAttributeName
      猜你喜欢
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2018-08-01
      • 1970-01-01
      • 2015-02-05
      • 1970-01-01
      相关资源
      最近更新 更多