NSMutableAttributedString 文本颜色无法正常工作

NSMutableAttributedString text color not working correctly

我有以下 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 工具 "Fix" 添加了 kCT 代码。字体名称和大小似乎有效。

修复程序为您提供了错误的密钥。您想改用这样的东西:

timeduration.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: timeduration.length))

其他人也一样。

您使用的键用于较低级别的核心文本内容。

你可以这样做,希望问题得到解决:-

let label = UILabel()
let labelText = "String Text"

let strokeTextAttributes = [
     NSAttributedStringKey.strokeColor : UIColor.black,
     NSAttributedStringKey.foregroundColor : UIColor.white,
     NSAttributedStringKey.strokeWidth : -2.0,
     NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
   ] as [NSAttributedStringKey : Any]

label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)

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

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))