在 Swift 中全局设置 NavigationItem titleView Image

Set NavigationItem titleView Image Globally in Swift

我正在尝试为我的应用程序中的导航控制器设置一个恒定状态。我成功地在我的 App Delegate 中声明了颜色并在整个应用程序中工作,但是我很难将徽标设置为 titleView。我可以在单独的视图控制器中轻松地做到这一点,而不是在全局范围内。

这是我的 App Delegate 中的内容:

    let logo = UIImage(named: "Logo")
    let imageView = UIImageView(image: logo)
    imageView.frame = CGRect(x: 0, y: 0, width: 0, height: 20)
    imageView.contentMode = UIViewContentMode.ScaleAspectFit

    // It's this line which errors and doesn't work
    navigationItem.titleView = imageView

更新:

感谢下面的回答,我现在明白按照描述这是不可能的。我已经将 imageView 的创建和设置放在一个全局函数中,然后在我需要的每个视图中只调用它一行。我认为这比在每个视图上重写以上所有内容更有效。

AppDelegate 没有名为 navigationItem 的成员变量,这是导致错误的原因。 navigationItem 是 UIViewController 的成员变量,这就是您能够在 ViewController 中使用它的原因。来自 Apple 的文档:

This is a unique instance of UINavigationItem created to represent the view controller when it is pushed onto a navigation controller. The first time the property is accessed, the UINavigationItem object is created. Therefore, you should not access this property if you are not using a navigation controller to display the view controller. To ensure the navigation item is configured, you can either override this property and add code to create the bar button items when first accessed or create the items in your view controller's initialization code.