2014-10-28 98 views
6

我想更改導航欄中的字體。但是下面的代碼不起作用,它會導致應用程序崩潰。更改Swift導航欄中的字體

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Lato-Light.ttf", size: 34)!] 

    return true 
} 

我收到以下錯誤:

致命錯誤:unexpectedly found nil while unwrapping an Optional value(lldb)

我確實增加了字體拉託-Light.ttf我的項目,所以它應該是能夠找到它。

回答

15

UIFont()是一個failable initalizer,它可能由於幾個原因失敗。使用!強制解包會導致應用崩潰。

更好的單獨初始化和檢查的成功:

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

,並檢查您的字體文件包含在捆綁資源。

Common Mistakes With Adding Custom Fonts to Your iOS App

+0

我嘗試添加一個println(「代碼執行」),它不打印到控制檯如此明確的代碼不執行的一部分。我在我的應用程序中使用字體,所以我知道它在那裏。我想知道爲什麼它找不到字體? – 2014-10-28 10:32:20

+0

檢查項目目標並查看它是否包含在捆綁資源中。 – zisoft 2014-10-28 10:33:12

+0

如何檢查它是否包含在內?對不起,我對此有點新。 – 2014-10-28 10:43:00

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

}