ios - 在 Swift 中更改导航栏中的字体

标签 ios swift fonts uinavigationbar

我想更改导航栏中的字体。但是,以下代码不起作用,它会导致应用程序崩溃。

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

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

     return true
}

我收到以下错误:

fatal error :在展开可选值 (lldb) 时意外发现 nil

我确实已将字体 Lato-Light.ttf 添加到我的项目中,因此它应该能够找到它。

最佳答案

UIFont() 是一个可失败的初始化器,它可能由于多种原因而失败。使用 ! 强制解包会使您的应用崩溃。

最好单独初始化它并检查是否成功:

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

关于ios - 在 Swift 中更改导航栏中的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26605796/

相关文章:

html - PDF 和 HTML 中显示的字体不同

ios - swift : Calling an init from another init

android - 如何在 Flutter 中制作水平数字选择器小部件?

ios - 横向模式下的 UINavigationBar 高度未完全显示

javascript - 如何发现字体类型?

java - 单选按钮和字体更改

ios - 在 Swift 中获取 RLMObject 的通用方法

iphone - 在 UITableViewCell 中设置 textLabel 的宽度

ios - 快速获取collectionView中心单元格的indexPath?

SwiftUI - SwiftUI 中是否有等效的 popViewController?