Error when instantiating a UIFont in an text attributes dictionary

后端 未结 4 944
北恋
北恋 2020-12-11 01:58

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

let barButton = UIBarButtonItem.appearance()
barButton.setTitleTextAttributes([NSFon         


        
相关标签:
4条回答
  • 2020-12-11 02:08

    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]
    

    }

    0 讨论(0)
  • 2020-12-11 02:15

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

    You have to unwrap it and check:

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

    UPDATED for Swift 3

    if let font = UIFont(name: "AvenirNext", size: 15) {
        barButton.setTitleTextAttributes([NSFontAttributeName:font], for: .normal)
    }
    
    0 讨论(0)
  • 2020-12-11 02:16

    Setting Custom font is little bit tricky, since they don't have font and title properties. Hope this following answer will help you.

    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
    
    0 讨论(0)
  • 2020-12-11 02:21
    if let font : UIFont = UIFont(name: "Roboto-Regular", size: 15)
            {
                cancelBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
                doneBarButton.setTitleTextAttributes([NSFontAttributeName: font], forState: UIControlState.Normal)
    
            }
    
    0 讨论(0)
提交回复
热议问题