在文本属性字典中实例化UIFont时出错

时间:2014-10-21 09:46:05

标签: ios swift cocoa-touch compiler-errors uibarbuttonitem

我正在尝试设置UIBarButtonItem的字体,如此:

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

但它会抛出编译错误:

  

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

调用'init'

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

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

但看起来它不可分配

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:27)

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

你需要打开它并检查:

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)
}

答案 1 :(得分:2)

设置自定义字体有点棘手,因为它们没有fonttitle属性。希望以下答案能为您提供帮助。

let font = UIFont(name: "<your_custom_font_name>", size: <font_size>)
var leftBarButtonItem = UIBarButtonItem(title: "<font_hex_code>", style: UIBarButtonStyle.Plain, target: self, action: "buttonClicked:")
leftBarButtonItem.setTitleTextAttributes([NSFontAttributeName:font!], forState: UIControlState.Normal)
self.navigationItem.leftBarButtonItem = leftBarButtonItem

答案 2 :(得分:1)

if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15)
        {
            cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
            doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)

        }

答案 3 :(得分:0)

使用Swift 4

不推荐使用NSFontAttributeName ,您可以使用NSAttributedStringKey值来设置属性。

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

}