前景色不适用于属性文本

Nom*_*sta 5 uilabel ios swift

我想在里面组合图像和文字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))
Run Code Online (Sandbox Code Playgroud)

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

let attributedText = NSMutableAttributedString(string: " ")
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*lly 1

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

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

然后image.withRenderingMode(...)你可以简单地写:

attachment.image = image.add_tintedImage(with: .white, style: ADDImageTintStyleKeepingAlpha)
Run Code Online (Sandbox Code Playgroud)