Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change font in navigation bar in Swift

I'd like to change the font in the navigation bar. However the following code doesn't work, it causes the app to crash.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Lato-Light.ttf", size: 34)!]

     return true
}

I am getting the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value(lldb)

I have indeed added the font Lato-Light.ttf to my project so it should be able to find it.

like image 897
Lasse Kristensen Avatar asked Oct 28 '14 10:10

Lasse Kristensen


People also ask

How do I change the font style of the navigation bar title in Swift?

let navigation = UINavigationBar. appearance() let navigationFont = UIFont(name: "Custom_Font_Name", size: 20) let navigationLargeFont = UIFont(name: "Custom_Font_Name", size: 34) //34 is Large Title size by default navigation. titleTextAttributes = [NSAttributedStringKey. foregroundColor: UIColor.

How do I add fonts to Xcode?

Add the Font File to Your Xcode Project To add a font file to your Xcode project, select File > Add Files to “Your Project Name” from the menu bar, or drag the file from Finder and drop it into your Xcode project. You can add True Type Font (. ttf) and Open Type Font (. otf) files.


2 Answers

UIFont() is a failable initalizer, it may fail due to several reasons. A forced unwrap using ! crashes your app.

Better initialize it separately and check for success:

if let font = UIFont(name: "Lato-Light.ttf", size: 34) {
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font]
}

And check if your font file is included in the bundle resources.

Common Mistakes With Adding Custom Fonts to Your iOS App

like image 166
zisoft Avatar answered Sep 16 '22 17:09

zisoft


import UIKit

class TestTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        configureView()

    }

    func configureView() {

        // Change the font and size of nav bar text
        if let navBarFont = UIFont(name: "HelveticaNeue-Thin", size: 20.0) {
            let navBarAttributesDictionary: [NSObject: AnyObject]? = [
                NSForegroundColorAttributeName: UIColor.whiteColor(),
                NSFontAttributeName: navBarFont
            ]
            navigationController?.navigationBar.titleTextAttributes = navBarAttributesDictionary
        }
    }

}
like image 36
Durul Dalkanat Avatar answered Sep 17 '22 17:09

Durul Dalkanat