6
votes

I used this code

    self.navigationController?.navigationBar.titleTextAttributes =
        [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20),
        NSForegroundColorAttributeName: UIColor.whiteColor()]

and I'm getting error "Could not find an overload for “init” that accepts the supplied arguments"

3
Slightly different question, but essentially the same problem: stackoverflow.com/questions/26499815/…Martin R

3 Answers

15
votes

UIFont(name:size:) is now a failable initializer -- it will return nil if it can't find that font and crash your app if you unwrap the return value. Use this code to safely get the font and use it:

if let font = UIFont(name: "HelveticaNeue-Light", size: 20) {
    self.navigationController?.navigationBar.titleTextAttributes = 
            [NSFontAttributeName: font, 
             NSForegroundColorAttributeName: UIColor.whiteColor()]
}
0
votes

Use this

self.navigationController?.navigationBar.titleTextAttributes =
        [NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20)!,
        NSForegroundColorAttributeName: UIColor.whiteColor()!]

or this one

if let font = UIFont(name:"HelveticaNeue-Light", size: 20.0) {
    self.navigationController?.navigationBar.titleTextAttributes  = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: font]
}
0
votes

Another approach is to build up a dictionary before setting titleTextAttributes. This just avoids you the else(s), which would be more beneficial in cases where you wanted to set further parameters also using failable initialisers. Eg:

var attributes : [NSObject : AnyObject] = [NSForegroundColorAttributeName : UIColor.whiteColor()]

if let font = UIFont(name: "Helvetica", size: 20) {
    attributes[NSFontAttributeName] = font
}

if let someData = NSData(contentsOfFile: "dataPath") {
    attributes["imageData"] = someData
}

self.myObject.attributes = attributes