NSAttributedStringKey在Swift 4中的错误。

8

更新到Swift 4后,我在这段代码上遇到了错误

    attributes["NSFont"] = font
    attributes["NSColor"] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

无法使用类型为“[NSAttributedStringKey:Any]”的值订阅类型为“String”的索引

我已经通过将["NSFont"]替换为NSAttributedStringKey.font来修复第一行,但是我不确定如何修复第二行。


NSAttributedStringKey.backgroundColor,NSAttributedStringKey.foregroundColor - Dixit Akabari
attributes["NSFont"] 这种方式不被推荐使用。对于另一个,请使用 NSFontAttributeNameNSForegroundColorAttributeName。如果明天 iOS SDK 决定将值从 NSFont 更改为 UIFont(这似乎更符合“iOS”),那该怎么办?这就是为什么首先不推荐使用该代码的原因。然后在 Swift 4 中,使用相应的 NSAttributedStringKey - Larme
3个回答

19

在Swift 4中,NSAttributedString的表示方式已经彻底改变。

如果你还没有这样做,请将属性字典 - attributes类型从[String : Any]更换为[NSAttributedStringKey : Any][NSAttributedString.Key : Any]

如果你正在使用Swift 4.2或更新版本,请尝试以下代码:

attributes[NSAttributedString.Key.font] = font
attributes[NSAttributedString.Key.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

Swift 4.0 & 4.1:

attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

以下是Apple文档中的说明:NSAttributedString.Key


3
使用NSAttributedStringKey.foregroundColor作为第二个参数,键不再是字符串,而是枚举常量。
attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)

你可以在NSAttributedStringKey的官方文档中找到所有的键。

1

对于Swift 3.3,NSForegroundColorAttributeNameNSFontAttributeName等内容

NSAttributedString(string: "text", attributes: [NSForegroundColorAttributeName : UIColor.white])

对于Swift 4.0+

NSAttributedString(string: "text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接