【问题标题】:Foreground color not working for attributed text前景色不适用于属性文本
【发布时间】:2018-04-18 09:02:06
【问题描述】:

我想在UILabel 中合并图像和文本。为了实现这一点,我正在使用这部分代码:

let attributedText = NSMutableAttributedString(string: "")
let attachment = NSTextAttachment()
attachment.image = image.withRenderingMode(.alwaysTemplate)
attachment.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
attributedText.append(NSAttributedString(attachment: attachment))
attributedText.append(NSMutableAttributedString(string: "test",
attributedText.addAttribute(NSAttributedStringKey.foregroundColor,
                value: UIColor.white,
                range: NSMakeRange(0, attributedText.length))

文本具有白色前景色,但不幸的是图像仍为原始颜色。有趣的是,当我将第一行更改为此(初始化程序中的空白)时:

let attributedText = NSMutableAttributedString(string: " ")

然后一切正常。但问题是标签内的整个文本由于空格而偏移。如何在不添加空格的情况下更改图像颜色?

【问题讨论】:

  • 如果您使用有效的方法(使用空格)然后使用attributedText.deleteCharacters(in: NSMakeRange(0,1)) 从字符串中删除空格,它是否有效?就像在这个答案中:stackoverflow.com/a/44769610/1298835
  • 不,删除第一个字符后图像颜色错误。我也不认为你提到的那个问题是重复的。
  • 很公平。根据相关问题,这是 2015 年的错误。它可能直到现在才修复.. 希望我的答案中的解决方法有所帮助,或者其他人知道不需要第三方框架的更好方法。跨度>
  • 你可以试试这个答案stackoverflow.com/questions/14287386/…

标签: ios swift uilabel


【解决方案1】:

您必须使用图形上下文来反转颜色。我可能会将其作为UIImage 的扩展名。

示例swift代码如下。

extension UIImage {
    func imageWithColor(color:UIColor) -> UIImage {
        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height);
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.clip(to: rect, mask: self.cgImage!)
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let imageFromCurrentContext = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return UIImage(cgImage: imageFromCurrentContext!.cgImage!, scale: 1.0, orientation:.downMirrored)
    }
}

【讨论】:

    【解决方案2】:

    这种行为似乎是 UIKit 中的一个错误。唉,我不知道解决方案,希望其他人知道,但现在这里有一个解决方法:

    您可以在将图像添加为文本附件之前为其着色。一个简单的方法是使用第三方框架,例如这个:https://github.com/vilanovi/UIImage-Additions

    那么你可以简单地写而不是image.withRenderingMode(...)

    attachment.image = image.add_tintedImage(with: .white, style: ADDImageTintStyleKeepingAlpha)
    

    【讨论】:

      【解决方案3】:

      原来 UIKit 中的 bug 仍然存在,但为避免因空格引起的偏移,您可以使用空字符串代替空格。 做吧:

      let attributedText = NSMutableAttributedString(string: "\0")
      

      而不是

      let attributedText = NSMutableAttributedString(string: " ")
      

      【讨论】:

        猜你喜欢
        • 2016-04-22
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多