【发布时间】: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 年的错误。它可能直到现在才修复.. 希望我的答案中的解决方法有所帮助,或者其他人知道不需要第三方框架的更好方法。跨度>