NSFontAttributeName vs NSAttributedStringKey.font
我在使用一段时间的库中使用Swift代码时遇到了一些麻烦。 它似乎与某种版本冲突有关,但我不确定。
这是代码:
let attribMsg = NSAttributedString(string: msg, attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 23.0)])
这是我从编译器获得的错误消息:
Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font' Did you mean 'zone'? Fix(button)
在不同的项目中使用此代码,我注意到其中一些我没有得到错误消息,所有编译都没有任何问题。
我还注意到,如果我用以下代码替换上面的代码:
let attribMsg = NSAttributedString(string: msg, attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 23.0)])
有问题的项目将起作用,而其他项目(以前正在工作)显示另一条消息:
'NSFontAttributeName' has been renamed to 'NSAttributedStringKey.font'
换句话说,一些项目使用一种类型的代码,而另一些项目使用另一种类型。
不用说,每次从一个项目切换到另一个项目时,我都不想更改代码。
我改变项目的部署目标的实验似乎没有太大的区别。 所以我的问题是: 处理这个问题的方法是什么?
这些项目可能是Swift的不同版本。
在Swift 4中, NSFontAttributeName
已被NSAttributedStringKey.font
替换。
Swift 4.2
NSAttributedStringKey
重命名为NSAttributedString.Key
。 但是对于此特定问题,您需要获取原始值,因此解决方案将是NSAttributedString.Key.font.rawValue
看看这里有一个深入的解释: https : //stackoverflow.com/a/46459315/2440997