我正在尝试在SwiftUI中更改NavigationBar的背景颜色,我已经使用以下代码完成了这个任务。但是,我还没有弄清楚如何动态更改和更新导航栏的背景颜色。
这段代码给出了正确的结果,但是点击其中一个按钮来更改“Color”变量并不会更新“NavigationBar”的颜色。这是因为在初始化时,导航栏保留了所有的特性,所以我需要找到一种方法在之后更改这些特性,并且如果可能的话,在更改颜色时进行动画过渡。谢谢任何帮助!
struct ContentView: View {
@State var color: Color = .red
init() {
let navbarAppearance = UINavigationBarAppearance()
navbarAppearance.largeTitleTextAttributes = [.foregroundColor: UIColor.white]
navbarAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
navbarAppearance.backgroundColor = UIColor(color)
UINavigationBar.appearance().standardAppearance = navbarAppearance
UINavigationBar.appearance().compactAppearance = navbarAppearance
UINavigationBar.appearance().scrollEdgeAppearance = navbarAppearance
}
var body: some View {
NavigationView {
VStack(spacing: 20) {
Button(action: { color = .blue }) {
Text("Blue")
.font(.title)
.bold()
.foregroundColor(.white)
.frame(width: 100)
.padding()
.background(Color.blue)
.cornerRadius(15)
}
Button(action: { color = .red }) {
Text("Red")
.font(.title)
.bold()
.foregroundColor(.white)
.frame(width: 100)
.padding()
.background(Color.red)
.cornerRadius(15)
}
}
.offset(y: -50)
.navigationTitle("My Navigation")
}
}
}
这段代码给出了正确的结果,但是点击其中一个按钮来更改“Color”变量并不会更新“NavigationBar”的颜色。这是因为在初始化时,导航栏保留了所有的特性,所以我需要找到一种方法在之后更改这些特性,并且如果可能的话,在更改颜色时进行动画过渡。谢谢任何帮助!