[英]Change font in navigation bar in 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)
我确实已经将字体Lato-Light.ttf添加到了我的项目中,因此它应该能够找到它。
UIFont()
是一个失败的初始化器,由于多种原因它可能会失败。 强制拆包使用!
使您的应用程序崩溃。
最好单独初始化并检查是否成功:
if let font = UIFont(name: "Lato-Light.ttf", size: 34) {
UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: font]
}
并检查您的字体文件是否包含在捆绑软件资源中。
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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.