使用swift 4的NSAttributedStringKey错误

问题描述 投票:6回答:3

更新到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来修复第一行,但我不知道如何修复第二行。

ios swift swift4 nsattributedstring nsattributedstringkey
3个回答
14
投票

在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


2
投票

使用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找到所有的钥匙。


0
投票

对于Swift 3.3,NSForegroundColorAttributeNameNSFontAttributeName之类的

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

适用于Swift 4.0+

NSAttributedString(string: "text", attributes: [NSAttributedStringKey.foregroundColor : UIColor.white])
© www.soinside.com 2019 - 2024. All rights reserved.