NSFontAttributeName vs NSAttributedStringKey.font

怎甘沉沦 提交于 2019-12-21 09:59:29

问题


I am having some trouble with Swift code in a library I have been using for a while. It seems related to some kind of version conflict, but I am not sure.

Here is the code:

let attribMsg = NSAttributedString(string: msg,
                               attributes: [NSAttributedStringKey.font:UIFont.systemFont(ofSize: 23.0)])

Here is the error message I get from the compiler:

Type 'NSAttributedStringKey' (aka 'NSString') has no member 'font'
    Did you mean 'zone'?  Fix(button)

Using this code in different project I noticed that on some of them I do not get the error message and it all compiles without any problem.

I also noticed that if I replace the above code by the following:

let attribMsg = NSAttributedString(string: msg,
                               attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 23.0)])

The projects with a problem will work while the others(previously working) show this other message:

'NSFontAttributeName' has been renamed to 'NSAttributedStringKey.font'

In other words some projects work with one type of code and some others work with the other type.

Needless to say that I do not want to change the code each time I switch from one project to another.

The experiments I made changing the Deployment Target of the project do not seem to make much difference. So comes my question: What is the way to handle this issue?


回答1:


The projects are probably in different versions of Swift.

In Swift 4, NSFontAttributeName has been replaced with NSAttributedStringKey.font.




回答2:


Swift 4.2

NSAttributedStringKey renamed NSAttributedString.Key. However for this particular issue you need to get the raw value so the solution would be NSAttributedString.Key.font.rawValue

Take a look here for an in-depth explanation: https://stackoverflow.com/a/46459315/2440997



来源:https://stackoverflow.com/questions/46966681/nsfontattributename-vs-nsattributedstringkey-font

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!