【问题标题】:Programmatically set navigation bar color and height in iOS15iOS15中以编程方式设置导航栏颜色和高度
【发布时间】:2022-01-16 16:43:52
【问题描述】:

我对 swift 非常陌生,正在构建导航视图。以下是我遇到的。

currentView

  1. 导航栏背景颜色只有部分黄色。我怎样才能让它上面的部分也变成黄色?

section should be yellow

下面是我在viewController 中使用的代码。我也尝试过navigation controller,但它不起作用。

self.navigationController?.navigationBar.backgroundColor = UIColor.yellow

  1. 如何设置导航栏的高度?搜索按钮(navigationItem.titleView)就在导航栏的中间,我想通过设置导航栏的高度来给它更多的空间。下面的代码是我尝试过但不起作用的代码:(

self.tabBarController?.tabBar.frame.size.height = 50

谢谢。

【问题讨论】:

    标签: ios swift ios15


    【解决方案1】:

    您还必须更改状态栏颜色。您可以使用以下 UIApplication 扩展来完成此操作

    extension UIApplication {
        var statusBarView: UIView? {
            if responds(to: Selector(("statusBar"))) {
                return value(forKey: "statusBar") as? UIView
            }
            return nil
        }
    }
    

    像这样使用上面的扩展:

    UIApplication.shared.statusBarView?.backgroundColor = .yellow
    

    适用于 iOS 13 及更高版本

    使用 UINavigationController 扩展来改变状态栏颜色:

    extension UINavigationController {
        func setStatusBar(backgroundColor: UIColor) {
            let statusBarFrame: CGRect
            if #available(iOS 13.0, *) {
                statusBarFrame = view.window?.windowScene?.statusBarManager?.statusBarFrame ?? CGRect.zero
            } else {
                statusBarFrame = UIApplication.shared.statusBarFrame
            }
            let statusBarView = UIView(frame: statusBarFrame)
            statusBarView.backgroundColor = backgroundColor
            view.addSubview(statusBarView)
        }
    }
    
    navigationController?.setStatusBar(backgroundColor: .yellow)
    

    【讨论】:

    • 如果它对您有帮助,请投票支持我的答案,并通过给予“绿权”将其添加到正确答案中。谢谢:)
    • 非常感谢。这个对我有用。但是有没有办法只增加导航栏的高度? (第一张图中的黄色区域)
    • @LoLo 我尝试了很多来增加导航栏的高度,但我做不到。一旦完成,我会 ping 你。谢谢
    • @LoLo 而不是增加导航栏的大小,我建议您隐藏导航栏并在其上添加uiview 和所有其他内容以从界面生成器或xib 创建您的搜索栏文件。在导航栏中添加子视图以增加高度并为其赋予颜色有点棘手,所以只需隐藏它当没有导航栏时,您不需要在代码中编写上述内容。只需将颜色分配给 uiview。
    • 知道了。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2017-12-30
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-14
    相关资源
    最近更新 更多