Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

swift - NSFontAttributeName has changed to String

i'm trying to style the navigation bar properly, i need to change the font to helvetica neue with a size point of 19. I've ever used this code but i've notice that now doesn't work as well:

navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 19)]

this happens because the type of NSFontAttributeName has changed to String, i've tried to fix it with

navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: "HelveticaNeue-Light, 19"]

but the compiler continue to give me an error related to point size in font, how can i fix it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The UIFont constructor is returning an optional (UIFont?) which you must unwrap to use. Add ! if you're sure you have a valid font name:

Swift 4.2:

navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "HelveticaNeue-Light", size: 19)!]

Swift 4:

navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "HelveticaNeue-Light", size: 19)!]

Swift 3:

navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 19)!]

Note: If you are setting a font with a static name in your code, then force unwrapping is safe once you’ve verified you’re using a valid font name. If you are getting the font name from an external source (the user or a server), you will want to use optional binding such as if let font = UIFont(... or guard let font = UIFont(... to safely unwrap the font before use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...