Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when instantiating a UIFont in an text attributes dictionary

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:

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...]` 

but it appears that it isn't assignable

How can I resolve this?

like image 372
Eilon Avatar asked Oct 21 '14 09:10

Eilon


3 Answers

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)
}
like image 53
zisoft Avatar answered Oct 02 '22 09:10

zisoft


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
like image 40
Sandeep Ankam Avatar answered Oct 02 '22 07:10

Sandeep Ankam


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

        }
like image 27
Alvin George Avatar answered Oct 02 '22 09:10

Alvin George