8

更新到 Swift 4 后,此代码出现错误

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

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

我能够通过替换来修复第一行["NSFont"]NSAttributedStringKey.font但我不确定如何修复第二行。

4

3 回答 3

19

在 swift 4 - NSAttributedString 表示完全改变。

替换你的属性字典 -attributes类型,从[String : Any][NSAttributedStringKey : Any][NSAttributedString.Key : Any],如果你还没有完成。

试试这个

斯威夫特 4.2+:

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

斯威夫特 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

于 2018-01-18T13:00:33.880 回答
3

用于NSAttributedStringKey.foregroundColor第二个,键不再是字符串,而是枚举常量。

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

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

于 2018-01-18T12:55:06.527 回答
1

对于 Swift 3.3, NSForegroundColorAttributeName,NSFontAttributeName

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

对于 Swift 4.0+

NSAttributedString(string: "text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
于 2018-09-07T06:36:00.207 回答