更新到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
来修复第一行,但我不知道如何修复第二行。
在swift 4中 - NSAttributedString表示完全改变了。
如果你还没有,请将你的属性字典 - attributes
类型,从[String : Any]
替换为[NSAttributedStringKey : Any]
或[NSAttributedString.Key : Any]
。
试试吧
attributes[NSAttributedString.Key.font] = font
attributes[NSAttributedString.Key.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)
attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)
以下是Apple文档中的说明:NSAttributedString.Key
使用NSAttributedStringKey.foregroundColor
作为第二个,键不再是字符串,而是枚举常量。
attributes[NSAttributedStringKey.font] = font
attributes[NSAttributedStringKey.foregroundColor] = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1)
你可以在official docs for NSAttributedStringKey找到所有的钥匙。
对于Swift 3.3,NSForegroundColorAttributeName
,NSFontAttributeName
之类的
NSAttributedString(string: "text", attributes: [NSForegroundColorAttributeName : UIColor.white])
适用于Swift 4.0+
NSAttributedString(string: "text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])