Skip to main content
 首页 » 操作系统

ios之'UINavigationController ' does not have a member named ' 导航栏'

2024年01月01日44虾米姐

我目前正在尝试使用以下代码更改 UINavigationBar 标题的字体,但在构建时遇到了错误:

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

错误

'UINavigationController?' does not have a member named 'navigationBar' 

ViewController.swift

import UIKit 
 
class ViewController: UIViewController { 
 
    override func viewDidLoad() { 
        super.viewDidLoad() 
        // Do any additional setup after loading the view, typically from a nib. 
        self.navigationController.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "DroidSerif", size: 20)] 
    } 
 
    override func didReceiveMemoryWarning() { 
        super.didReceiveMemoryWarning() 
        // Dispose of any resources that can be recreated. 
    } 
 
 
} 

ViewController 嵌入在 Navigation Controller 中。抱歉,这是我第一次尝试 Swift。考虑坚持使用 Objective-C。

请您参考如下方法:

看来你的属性(property)navigationController (在 Swift 中通常不需要 self)是 UINavigationController? 类型(注意 ? )。这意味着它是一个可选变量,也可以是 nil。你必须使用 !打开它。将您的线路更改为

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

参见 here了解更多。