我希望能够在 SwiftUI 中为 NavBar 和 navigationBarItems 设置自定义颜色。这是导航栏项的代码:
.navigationBarItems(leading: EditButton(), trailing: Button(action: {
self.showingAddScreen.toggle()
}) {
Image(systemName: "plus")
})
.sheet(isPresented: $showingAddScreen) {
NavigationView {
AddTaskView().environment(\.managedObjectContext, self.moc)
}
}
我使用以下代码创建了一个扩展,它在 NavigationBar 背景颜色上效果很好,但它不会改变 navigationBarItems 的颜色——它们具有默认的蓝色按钮。
extension UINavigationController {
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let standardAppearance = UINavigationBarAppearance()
standardAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)
let scrollEdgeAppearance = UINavigationBarAppearance()
scrollEdgeAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)
let compactAppearance = UINavigationBarAppearance()
compactAppearance.backgroundColor = UIColor(red: 66/255, green: 116/255, blue: 147/255, alpha: 1.0)
navigationBar.standardAppearance = standardAppearance
navigationBar.scrollEdgeAppearance = scrollEdgeAppearance
navigationBar.compactAppearance = compactAppearance
navigationBar.tintColor = UIColor.white
}
}
更改 navigationBarItems 颜色的正确方法是什么?