How do i change navigationBar font in Swift?

2019-01-31 12:13发布

How do I change the NavigationBar font in Swift?

This is what I have tried so far, but receiving an error (I have correctly implemented CaviarDreams to the project):

self.navigationController.navigationBar.titleTextAttributes = NSFontAttributeName[UIFont .fontWithName(CaviarDreams.ttf, size: 20)]

Error says: Use of unresolved identifier 'CaviarDreams

Sorry if the question is extremely bad.

8条回答
Animai°情兽
2楼-- · 2019-01-31 12:28

Try this:

self.navigationController.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "CaviarDreams", size: 20)!]

Edit: Now, UIFont must be unwrapped to be able to be used here.

查看更多
不美不萌又怎样
3楼-- · 2019-01-31 12:30

For Swift 2.3

self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Roboto-Bold", size: 20.0)!, NSForegroundColorAttributeName : UIColor.whiteColor()];
查看更多
冷血范
4楼-- · 2019-01-31 12:32

Now you have to unwrap (!) it first so its not of type UIFont?:

self.navigationController.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "<font-name>", size: <size>)!]
查看更多
倾城 Initia
5楼-- · 2019-01-31 12:32

Swift 4

if let font = UIFont(name: "FontName", size: 16) {

 self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: font]

}

Or as the other answer recommended doing it on the AppDelegate:

  if let font = UIFont(name: "FontName", size: 16) {

    UINavigationBar.appearance().titleTextAttributes = [
          NSAttributedStringKey.font: font]

}
查看更多
Rolldiameter
6楼-- · 2019-01-31 12:34

Swift 4.2

 self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont(name: "Helvetica", size: 18.0)!]
查看更多
你好瞎i
7楼-- · 2019-01-31 12:37

Swift 2.0:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        UINavigationBar.appearance().titleTextAttributes = [
            NSFontAttributeName: UIFont(name: "Arial-Regular", size: 30)!
        ]

        return true
    }

Or

 override func viewDidLoad() {
  super.viewDidLoad()

  self.navigationController?.navigationBarHidden =  false
  self.title = "SAMPLE"

//Set Color
  let attributes: AnyObject = [ NSForegroundColorAttributeName: UIColor.redColor()]
  self.navigationController!.navigationBar.titleTextAttributes = attributes as? [String : AnyObject]


//Set Font Size
  self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Arial", size: 37.0)!];

 }
查看更多
登录 后发表回答