首页 > 解决方案 > NSMutableAttributedString 文本颜色无法正常工作

问题描述

我有以下 swift 4.1 代码:

    let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time");

    timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length));
    timeduration.addAttribute(kCTForegroundColorAttributeName as NSAttributedStringKey, value: UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range: NSRange(location: 0, length: timeduration.length));
    timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount));
    timeduration.addAttribute(kCTFontAttributeName as NSAttributedStringKey, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2));

我使用的是 Swift 3 并使用 Xcode 的工具迁移到 swift 4.1,但前景色似乎不起作用。XCode 工具“修复”添加了 kCT 代码。字体名称和大小似乎可以正常工作。

标签: iosiphoneswiftswift4ios11

解决方案


这是您的问题的解决方案。在 Swift 4.0 及更高版本中,有一个名为 NSAttributedStringKey 的结构,它定义了字符串属性的键。

let timeduration = NSMutableAttributedString.init(string: "a dynamic string of time")

timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 0, length: timeduration.length))

timeduration.addAttribute(NSAttributedStringKey.foregroundColor, value: 

UIColor(red: 200/255, green: 200/255, blue: 200/255, alpha: 1.0), range: 
NSRange(location: 0, length: timeduration.length))

timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 50), range: NSRange(location: 0, length: timecount))

timeduration.addAttribute(NSAttributedStringKey.font, value: UIFont.systemFont(ofSize: 25), range: NSRange(location: timecount, length: 2))

推荐阅读