Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xcode 6.1 titleTextAttributes

Tags:

swift

xcode6

so I am writing this app that has colorful navigationbars and the font of the title in that bars and the font of the UIBarButtonItems should be white and in a specific font. I used these 2 lines to accomplish that in the AppDelegate..

    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22), NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22), NSForegroundColorAttributeName : UIColor.whiteColor()], forState: .Normal)

But with Xcode 6.1 I get an error in each of these lines and I really don't know, what in means..

enter image description here

The text attributes are [NSObject: AnyObject]?. That's exactly what I wrote down.. Does anybody has a solution for this?

like image 572
Ben Avatar asked Oct 09 '14 07:10

Ben


1 Answers

I think the problem is because they've changed UIFont's initializer in 6.1 so it can return nil. That is correct behavior because if you enter wrong font name there is no way to instantiate UIFont. In this case your dictionary becomes [NSObject: AnyObject?] which is not the same with [NSObject: AnyObject]. You can first initialize fonts and then you can use if let syntax. Here is how to do this

let font = UIFont(name: "SourceSansPro-Regular", size: 22)
if let font = font {
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : font, NSForegroundColorAttributeName : UIColor.whiteColor()]
}

Or if you sure the font object is not gonna be nil you can use implicitly unwrapped optional syntax. In this case you are taking the risk of runtime crash. Here is how to do it.

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName : UIFont(name: "SourceSansPro-Regular", size: 22)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
like image 188
mustafa Avatar answered Sep 28 '22 09:09

mustafa