在文本属性字典中实例化UIFont时出错 [英] Error when instantiating a UIFont in an text attributes dictionary

查看:196
本文介绍了在文本属性字典中实例化UIFont时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置 UIBarButtonItem 的字体,如下所示:

I'm trying to set the font of the UIBarButtonItem like so:

let barButton = UIBarButtonItem.appearance()
barButton.setTitleTextAttributes([NSFontAttributeName: UIFont(name: "AvenirNext", size: 15], forState: UIControlState.Normal)

但它会抛出一个编译错误:

But it throws a compiler error saying:


无法使用参数列表类型调用'init'($ T7,forState:UIControlState)`

Cannot invoke 'init' with an argument list type '($T7, forState: UIControlState)`

我不知道是什么这意味着。我也试过了

and I have no idea what that means. I have also tried

barButton.titleTextAttributesForState(UIControlState.Normal) =[NSFontAttributeName...]` 

但看来它不可分配

我该如何解决这个问题?

How can I resolve this?

推荐答案

UIFont 的初始化程序返回一个可选,因为它可能由于拼写错误的字体名称等而失败。

The initializer of UIFont returns an optional because it may fail due to misspelled font name etc.

你必须打开并检查:

if let font = UIFont(name: "AvenirNext", size: 15) {
    barButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
}

更新为Swift 3

if let font = UIFont(name: "AvenirNext", size: 15) {
    barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
}

这篇关于在文本属性字典中实例化UIFont时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆