我需要能够按需更改 SwiftUI 视图中的颜色。这不是根据需要为视图中的对象切换颜色的问题,但是如何为 NavigationBar 外观属性做到这一点?这是我在视图初始化时设置导航栏外观的方法。点击按钮会更改按钮颜色,但不会更改导航栏的外观。使用不同的 theme1 值重新启动应用程序将显示正确的颜色,但点击按钮只会更改按钮颜色,而不会更改 NavBar 的外观。
struct ContentView: View {
@State private var theme1 = true
init() {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.titleTextAttributes = [.foregroundColor: theme1 ? UIColor.red : UIColor.yellow]
navBarAppearance.largeTitleTextAttributes = [.foregroundColor: theme1 ? UIColor.red : UIColor.yellow]
navBarAppearance.backgroundColor = theme1 ? UIColor.yellow : UIColor.red
UINavigationBar.appearance().standardAppearance = navBarAppearance
UINavigationBar.appearance().compactAppearance = navBarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navBarAppearance
UINavigationBar.appearance().tintColor = theme1 ? UIColor.red : UIColor.yellow
}
var body: some View {
NavigationView {
VStack {
Button("Toggle Style") {
theme1.toggle()
}
.padding(8)
.foregroundColor(theme1 ? Color(.red): Color(.yellow))
.background(RoundedRectangle(cornerRadius: 10)
.fill(theme1 ? Color(.yellow) : Color(.red)))
}
.navigationTitle("Theme Picker")
}
}
}