没有办法通过一条简单的线路将栏更改为您自己的本地暗模式。但是我们可以编写一个函数来完成与您想要的类似的事情。请注意,执行此类操作的正确方法是添加一个使用 trait 集合在不同全局视觉模式之间切换的条形样式和颜色的开关。
extension UIViewController {
enum NavigationBarStyle {
case dark, light
}
func setNavigationBar(style: NavigationBarStyle) {
guard let bar = view.subviews.first(where: { return $0 is UINavigationBar }) as? UINavigationBar else { return }
func set(item: UINavigationItem, color: UIColor) {
item.rightBarButtonItem?.tintColor = color
item.leftBarButtonItem?.tintColor = color
}
bar.barStyle = style == .dark ? .black : default
let color: UIColor = style == .dark ? .white : .black
for item in bar.items ?? [] {
bar.titleTextAttributes = [.foregroundColor: color]
set(item: item, color: color)
}
}
}
您需要确保已将导航栏添加到控制器的子视图中。我以编程方式做了类似的事情,但我想使用界面构建器是一样的。
let navbar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: 375, height: 45))
navbar.backgroundColor = UIColor.white
navbar.delegate = self
let navItem = UINavigationItem()
navItem.title = "Title"
navItem.leftBarButtonItem = UIBarButtonItem(title: "Left", style: .plain, target: self, action: nil)
navItem.rightBarButtonItem = UIBarButtonItem(title: "Right", style: .plain, target: self, action: nil)
navbar.setItems([navItem], animated: true)
view.addSubview(navbar)
最后,在一些动作或任何你喜欢的东西之后设置样式。使用;
setNavigationBar(style: .dark)