NSFontAttributeName已更改为String

Mon*_*WTF 35 string uinavigationbar swift

我正在尝试正确设置导航栏的样式,我需要将字体更改为helvetica neue,大小为19.我曾经使用过此代码,但我注意到现在不能正常工作:

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

发生这种情况是因为NSFontAttributeName的类型已更改为String,我试图修复它

navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: "HelveticaNeue-Light, 19"]
Run Code Online (Sandbox Code Playgroud)

但编译器继续给我一个与字体中的磅值相关的错误,我该如何解决?

vac*_*ama 97

UIFont构造函数返回一个可选的(UIFont?),你必须拆开包装使用.添加!如果你确定你有一个有效的字体名称:

Swift 4.2:

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

斯威夫特4:

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

斯威夫特3:

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

注意:如果您在代码中设置带有静态名称的字体,则在您确认使用的是有效字体名称后强制解包是安全的.如果从外部源(用户或服务器)获取字体名称,则需要使用可选的绑定,例如if let font = UIFont(...guard let font = UIFont(...在使用前安全地打开字体.

  • 这里需要改进错误消息. (4认同)

abd*_*lek 50

使用Swift 4 NSFontAttributeName不建议使用,可以使用NSAttributedStringKey值来设置属性.

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

随着Swift 4.2 NSAttributedStringKey改为NSAttributedString.Key.

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

有关NSAttributedStringKey的更多选项,您可以访问此链接https://developer.apple.com/documentation/foundation/nsattributedstringkey/