25
votes

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

6 Answers

43
votes

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)
10
votes

Swift 4:

UIBarButtonItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.white], for: .normal)
UINavigationBar.appearance().titleTextAttributes = [
            NSAttributedStringKey.foregroundColor: UIColor.white
        ]
2
votes

For Swift 3 you could try the following:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
1
votes

Swift 5

navBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:titleColor]
0
votes
    if let navFont = UIFont(name: "HelveticaNeue-Bold", size: 30.0) {
        let navBarAttributesDictionary: [NSObject: AnyObject]? = [
            NSForegroundColorAttributeName: UIColor.blackColor(),
            NSFontAttributeName: navFont
        ]
        navigationController?.navigationBar.titleTextAttributes = navBarAttributesDictionary
    }
0
votes

Swift 4:

if let navFont = UIFont(name: "Futura", size: 18) {
   let navBarAttributesDictionary: [NSAttributedStringKey: Any] = [
   NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): UIColor(netHex: Colors.BabyBlue.rawValue),
   NSAttributedStringKey(rawValue: NSAttributedStringKey.font.rawValue): navFont ]
   UINavigationBar.appearance().titleTextAttributes = navBarAttributesDictionary
}