【问题标题】:Custom UINavigationBar from AppDelegate来自 AppDelegate 的自定义 UINavigationBar
【发布时间】:2018-01-21 18:32:45
【问题描述】:

我制作了一个自定义 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
    }
}

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

let navigationBar  = UINavigationBar.customNavBar.appearance()

我想这样做的原因是因为我有一些其他的UIViewControllers(与我的TabViewController 不同),我想在其中手动添加 UINavigationBar 并且它必须看起来像自定义一个。

【问题讨论】:

  • 你在设置 UINavigationBar.appearance() 的属性吗?例如UINavigationBar.appearance().tintColor = .red
  • @andrehungaro 确实,但我想在我的应用程序委托中调用我的 customNavBar

标签: ios swift uinavigationbar navigationbar uiapplicationdelegate


【解决方案1】:

如果您想将导航栏自定义到那种程度,最好创建一个子类。问题是您需要手动将类名传递给任何需要使用它的导航控制器。如果需要,您可以对 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

【讨论】:

  • 如何在 AppDelegate 中使用 MyNavigationBar,以便在应用级别替换 NavigationBar?
  • 并非所有应用都有UINavigationController。你在使用故事板吗?
  • 我假设您在 AppDelegate 中创建应用程序范围的导航控制器并将其设置为 window.rootViewController 或类似的东西。
  • 所以使用我示例中的最后一行代码来创建您的导航控制器。
【解决方案2】:

我的代码错了 迅速你应该使用

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

然后

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

reference

【讨论】:

  • 快点怎么样?
  • 我明白你现在在做什么,但是我的问题是我已经有一个导航控制器分配给 rootviewcontroller。它实际上是一个 TabViewController
  • 是的,只需使用上面的 init() 方法并将其分配给您的自定义导航栏
  • 不确定我是否在关注你。下面是我的window?.rootViewController = MenuTabBarController(),其中class MenuTabBarController: UITabBarController
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 2016-11-30
  • 2010-10-16
  • 2012-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多