Search code examples
iosxcodeswiftuinavigationcontrollernavbar

Cannot Set Navigation Bar Font in Swift on Latest Xcode Version


The following code was running fine before updating to Xcode 6.1 to stay up with iOS 8.1:

override func viewDidAppear(animated: Bool) {  
     self.navigationController?.navigationBar.topItem?.title = "Home"
     self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34),  NSForegroundColorAttributeName: UIColor.whiteColor()]
}

The issue is specifically in NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)

and the error I'm getting here is:

! "Could not find an overload for 'init' that accepts the supplied arguments"

I found this original code on a different StackOverflow question and it was working as expected until this update (downloaded it yesterday). My font is indeed installed properly.

Should I be writing this code differently now, or is there an entirely new way in which I should set my Navigation Bar Font?

Thanks!


Solution

  • Whoops. I figured this out on my own:

    I needed an exclamation point following my declaration of the NSFontAttributeName as it requires a type "NSString!". Perhaps it only required an "NSString" before, but I have no issues now.

    Working line:

    NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 24)!
    

    Working full code:

    override func viewDidAppear(animated: Bool) {  
         self.navigationController?.navigationBar.topItem?.title = "Home"
         self.navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "Lobster 1.4", size: 34)!,  NSForegroundColorAttributeName: UIColor.whiteColor()]
    }
    

    Seems like a silly question now. Hope this helps someone else!