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..
The text attributes are [NSObject: AnyObject]?. That's exactly what I wrote down.. Does anybody has a solution for this?
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()]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With