Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing UINavigationBar font in Swift

I have a UINavigationBar with a title in the middle. I have added a custom font ("Comic_Andy.ttf") to my app (I have checked info.plist to make sure it's listed, and I have checked the Copy Bundle Resources to make sure it has been added), and I would like the title of the UINavigationBar to be displayed in that font. From what I can gather it seems as though I'm supposed to use this in my ViewController:

myNavigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Comic_Andy", size: 22)]

I placed that method in the viewDidLoad function of the ViewController.
I have also tried this in the didFinishLaunchingWithOptions function of the AppDelegate:

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Comic_Andy", size: 22)]


I am programming in Swift, in XCode 6 Beta 6. Many resources regarding this task have mentioned using a method called setTitleTextAttributes, which is nowhere to be seen. I can't figure it out for the life of me - I've probably spent close to 3 hours on it by now - I have checked every StackOverflow answer, every website, so please do not mark this as a duplicate.

Many thanks in advance!

like image 719
dcgoss Avatar asked Aug 24 '14 22:08

dcgoss


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.

How do I customize the navigation bar in Swift?

Go to the ViewController. swift file and add the ViewDidAppear method. a nav helper variable which saves typing. the Navigation Bar Style is set to black and the tint color is set to yellow, this will change the bar button items to yellow.

How do I change the font in SwiftUI?

Hold the command key and click the text to bring up a pop-over menu. Choose Show SwiftUI Inspector and then you can edit the text/font properties.


2 Answers

Instead of using myNavigationBar, try navigationController.navigationBar in the ViewController viewDidLoad function. It worked for me.

navigationController.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Comic_Andy", size: 22)]

If this doesn't work, try using the .ttf suffix.

navigationController.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Comic_Andy.ttf", size: 22)]

Good luck!

like image 177
trumpeter201 Avatar answered Oct 06 '22 18:10

trumpeter201


Can also be done for all NavigationBars with UINavigationBar.appearance().

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: Font.mediumFontName, size: 20)!]

like image 7
Rags93 Avatar answered Oct 06 '22 18:10

Rags93