Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing titleTextAttribute in swift

Every since i updated xcode i cant seem to change the titleTextAttribute. Now when i use following code i get this error:

could not find an overload init that accepts this supplied arguments

Code in appDelegate:

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Ubuntu", size: 17), NSForegroundColorAttributeName:UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: UIFont(name: "Ubuntu-Light", size: 15), NSForegroundColorAttributeName:UIColor.whiteColor()], forState: UIControlState.Normal)
like image 756
Peter Pik Avatar asked Nov 11 '14 15:11

Peter Pik


4 Answers

There was a recent change so that UIFont(name:size:) returns an optional UIFont instance. You'll need to unwrap them to get it to work. Using ! is the easiest way, but will get you a crash if the font isn't on the system. Try something like:

let navbarFont = UIFont(name: "Ubuntu", size: 17) ?? UIFont.systemFontOfSize(17)
let barbuttonFont = UIFont(name: "Ubuntu-Light", size: 15) ?? UIFont.systemFontOfSize(15)

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: navbarFont, NSForegroundColorAttributeName:UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: barbuttonFont, NSForegroundColorAttributeName:UIColor.whiteColor()], forState: UIControlState.Normal)
like image 91
Nate Cook Avatar answered Oct 13 '22 02:10

Nate Cook


Swift 4:

UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .normal)
UINavigationBar.appearance().titleTextAttributes = [
            NSAttributedStringKey.foregroundColor: UIColor.white
        ]
like image 41
Steve Moser Avatar answered Oct 13 '22 01:10

Steve Moser


Swift 5

navBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:titleColor]
like image 26
Sazzad Hissain Khan Avatar answered Oct 13 '22 02:10

Sazzad Hissain Khan


For Swift 3 you could try the following:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
like image 33
Andrey Kirsanov Avatar answered Oct 13 '22 00:10

Andrey Kirsanov