在iOS15中编程设置导航栏的颜色和高度



我是swift的新手,正在构建导航视图。下面是我遇到的。

currentView

  1. 导航栏背景颜色仅为部分黄色。我怎样才能使上面的部分也变成黄色

部分应为黄色

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

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

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

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

谢谢。

您还必须更改状态栏的颜色。你可以使用下面的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)

最新更新