2017-05-23 26 views
0

我知道這一定很簡單,但它躲避我:如何更改導航項目的字體?

我有一個UINavigationController中的代碼,它爲導航欄的標題設置字體以及背景顏色和顏色導航項目:

override func viewDidLoad() { 

    super.viewDidLoad() 

    let navigationBarAppearace = UINavigationBar.appearance() 

    navigationBarAppearace.tintColor = UIColor.white 
    navigationBarAppearace.barTintColor = UIColor(colorLiteralRed: 46/255, green: 99/255, blue: 201/255, alpha: 1.0) 
    navigationBarAppearace.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!] 

} 

但我無法獲取導航項目的字體更改。我已經嘗試了一些事情,包括(在相同的viewDidLoad中):

self.navigationItem.backBarButtonItem?.setTitleTextAttributes([ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!], for: UIControlState.normal)

以及(在使用導航欄:)

self.navigationController?.navigationItem.backBarButtonItem?.setTitleTextAttributes([ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!], for: UIControlState.normal)

的ViewControllers之一的viewDidLoad我在plist中有字體,並且正在項目的其他部分成功使用它。我假設我只是試圖做錯誤的方式,有人可以幫忙嗎?

回答

1

你可以改變所有UIBarButtonItems的外觀你UINavigationViewController類:

UIBarButtonItem.appearance().setTitleTextAttributes([NSFontAttributeName: font!], for: UIControlState.normal) 

看到更多細節在這裏:Change font of back navigation bar button

+0

太棒了,謝謝!完美的作品。 –

0

如果OpenSans是不是在plist文件,你會得到fatal error: unexpectedly found nil while unwrapping an Optional value

所以請嘗試

override func awakeFromNib() { 
    let navigationBarAppearace = UINavigationBar.appearance() 

    navigationBarAppearace.tintColor = UIColor.white 
    navigationBarAppearace.barTintColor = UIColor(colorLiteralRed: 46/255, green: 99/255, blue: 201/255, alpha: 1.0) 
    navigationBarAppearace.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "OpenSans", size: 17)!] 
} 

difference between awakeFromNib() and viewDidLoad() in swift