ios - 前景色不适用于属性文本

标签 ios swift uilabel

我想在 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: " ")

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

最佳答案

您必须使用图形上下文来反转颜色。我可能会将其作为 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)
    }
}

关于ios - 前景色不适用于属性文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132886/

相关文章:

ios - 如何在单击按钮后 2 秒呈现 AlertController

ios - 使用 Realm 快速保存图像数组

ios - 如何在 Swift 中创建一组委托(delegate)协议(protocol)项?

ios - subview (UILabel)放置在 super View (UITextView)中时不遵守约束

iOS uilabel 滚动时保持在屏幕上

iOS - 如何启用与 WebView 的用户交互

ios - adWhirl 的 actualadsize 方法没有返回正确的信息

swift - 我自己的自定义类中的扩展

ios - Swift - iOS - 共享单个数据源的多个 TableView Controller 。

ios - 在 UILabel 中获得一个看起来正常的 unicode 向下箭头,如下所示 ⬇