来自 AppDelegate 的自定义 UINavigationBar

Custom UINavigationBar from AppDelegate

我制作了一个自定义的 UINavigationBar,我想在全球范围内使用它。我在其他示例中看到,要全局设置 UINavigationBar 外观,您必须在 AppDelegate 中执行类似 let navigationBar = UINavigationBar.appearance() 的操作。然后你可以设置属性。就我而言,我已经在 class var 中设置了所有属性,如下所示:

extension UINavigationBar {
    class var customNavBar : UINavigationBar{
        let navigationBar = UINavigationBar()
        navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Avenir-Black", size: 40)!, NSForegroundColorAttributeName: UIColor.RED]

        //gets rid of black separation bar
        navigationBar.shadowImage = UIImage()
        navigationBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)

        //set the background color to white
        navigationBar.tintColor = UIColor.white
        navigationBar.isTranslucent = false
        return navigationBar
    }
}

现在,如何将 AppDelegate 的 UINavigationBar 设置为固有的这些属性。我的意思是在应用程序委托中有这样的东西。或者类似的当然。 在 AppDelegate 中:

let navigationBar  = UINavigationBar.customNavBar.appearance()

我想这样做的原因是因为我有一些其他的 UIViewControllers(不从我的 TabViewController 继续),我想在其中手动添加一个 UINavigationBar 和它必须看起来像定制的一样。

如果你想自定义你的导航栏到那个程度,你最好做一个子class。问题是您需要手动将 class 名称传递给需要使用它的任何导航控制器。如果需要,您可以对 UIToolbar 执行相同的操作,或者传递 nil 以使用默认值。

class MyNavigationBar: UINavigationBar {
    override init(frame: CGRect) {
        super.init(frame: frame)
        // configure your nav bar here
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

let navController = UINavigationController(navigationBarClass: MyNavigationBar.self, toolbarClass: nil)

供参考:https://developer.apple.com/documentation/uikit/uinavigationcontroller/1621866-init

我的代码有误 在 swift 你应该使用

NavController = UINavigationController.init(navigationBarClass: yoursubClass, toolbarClass: AnyClass?)

然后

if let window = self.window{
        window.rootViewController = NavController
 }

reference