Change font in navigation bar in Swift

I want to change the font in the navigation bar. However, the following code does not work; it causes the application 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 get the following error:

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

I really added the Lato-Light.ttf font to my project so that it can find it.

+6
source share
2 answers

UIFont() is a fail-safe initializer; it may not work for several reasons. Forced deployment with ! causes your application to crash.

It is better to initialize it separately and verify success:

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

And check if the font file is included in the package resources.

Common errors with adding custom fonts to your iOS app

+15
source
 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 } } } 
+2
source

Source: https://habr.com/ru/post/977330/


All Articles