NSFontAttributeName has changed to String

試著忘記壹切 提交于 2019-11-27 11:07:07

问题


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?


回答1:


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.




回答2:


With Swift 4 NSFontAttributeName is deprecated, you can use NSAttributedStringKey values to set attributes.

if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) {
  navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: fontStyle]
}

With Swift 4.2 NSAttributedStringKey is changed as NSAttributedString.Key.

if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) {
  navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: fontStyle]
}

For more options for NSAttributedStringKey you can visit this link https://developer.apple.com/documentation/foundation/nsattributedstringkey/




回答3:


Swift 4.2

NSAttributedStringKey has renamed to NSAttributedString.Key in Swift 4.2

if let fontStyle = UIFont(name: "HelveticaNeue-Light", size: 19) {
  navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: fontStyle]
}


来源:https://stackoverflow.com/questions/26572901/nsfontattributename-has-changed-to-string

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