【发布时间】:2021-11-14 14:59:24
【问题描述】:
我正在尝试更改 SwiftUI 中的 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 的颜色。这是因为在初始化时导航栏保持了它的所有特征,所以我需要找到一种方法来改变这些,如果可能的话,在改变颜色之间为这个过渡设置动画。感谢您的帮助!
【问题讨论】:
标签: swift swiftui uinavigationbar swiftui-navigationview uinavigationbarappearance