6

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"

1

3 Answers 3

15

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()]
}
Sign up to request clarification or add additional context in comments.

Comments

0

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]
}

1 Comment

You don't need the ! after UIcolor.whiteColor() as it doesn't return an optional. In fact, using it will give you a compiler error.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.