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