NSFontAttributeName 已更改为 String [英] NSFontAttributeName has changed to String
问题描述
我正在尝试正确设置导航栏的样式,我需要将字体更改为大小点为 19 的 Helvetica neue.我曾经使用过此代码,但我注意到现在效果不佳:
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)]
发生这种情况是因为 NSFontAttributeName 的类型已更改为 String,我已尝试使用
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?
推荐答案
UIFont
构造函数返回一个可选的 (UIFont?
),您必须打开它才能使用.添加 !
如果你确定你有一个有效的字体名称:
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)!]
注意:如果您在代码中使用静态名称设置字体,那么一旦您确认使用了有效的字体名称,强制展开是安全的.如果您从外部来源(用户或服务器)获取字体名称,您将需要使用可选绑定,例如 if let font = UIFont(...
或 guard let font = UIFont(...
以在使用前安全地解开字体.
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.
这篇关于NSFontAttributeName 已更改为 String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!