在我的项目中,我有两个颜色选择器,可以更改背景颜色和字体颜色。
纸张,我在其中更改颜色:
@ObservedObject var listColor: ListColor
ColorPicker("Hintergrund", selection: $listColor.bgColor)
ColorPicker("Text", selection: $listColor.textColor)
ContentView,其中应显示更改:
@ObservedObject private var listColor = ListColor()
VStack{
VStack{...}
.backgroundColor(listColor.bgColor)
.foregroundColor(listColor.textColor)
}
.navigationBarTitle(Text("Workout"), displayMode: .automatic)
.navigationBarColor(backgroundColor: listColor.bgColorNav, titleColor: listColor.textColorNav) // my own viewmodifier
.navigationBarItems(trailing:
Button(action: {
self.showSettings.toggle()
}) {
Text("Settings")
}
.sheet(isPresented: $showSettings){
SettingsView(listColor: listColor) //open View with the color pickers
})
我还有自己的ViewModifer,它可以更改导航栏的背景颜色和字体颜色。
struct NavigationBarModifier: ViewModifier {
var backgroundColor: UIColor?
var titleColor: UIColor?
init(backgroundColor: UIColor?, titleColor: UIColor?) {
self.backgroundColor = backgroundColor
let coloredAppearance = UINavigationBarAppearance()
coloredAppearance.configureWithTransparentBackground()
coloredAppearance.backgroundColor = backgroundColor
coloredAppearance.titleTextAttributes = [.foregroundColor: titleColor ?? .white]
coloredAppearance.largeTitleTextAttributes = [.foregroundColor: titleColor ?? .white]
UINavigationBar.appearance().standardAppearance = coloredAppearance
UINavigationBar.appearance().compactAppearance = coloredAppearance
UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
Color(self.backgroundColor ?? .clear)
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
问题在于;正常的";背景和字体颜色会更改,但不会在导航栏中更改。我认为问题是我自己的导航栏ViewModifier没有重新加载视图。我将颜色保存在UserDefaults中;当我再次启动应用程序时,更改将显示在导航栏中。
不要在ViewModifier中使用普通变量,而是声明到Color
对象的绑定。然后,如果包装后的值发生更改,视图(在本例中为导航栏(将自动重新绘制。
我的工作示例:
import SwiftUI
struct NavigationBarModifier: ViewModifier {
var backgroundColor: Binding<Color>
init(backgroundColor: Binding<Color>) {
self.backgroundColor = backgroundColor
}
func body(content: Content) -> some View {
ZStack{
content
VStack {
GeometryReader { geometry in
self.backgroundColor.wrappedValue
.frame(height: geometry.safeAreaInsets.top)
.edgesIgnoringSafeArea(.top)
Spacer()
}
}
}
}
}
extension View {
func navigationBarColor(_ bgColor: Binding<Color>) -> some View {
self.modifier(NavigationBarModifier(backgroundColor: bgColor))
}
}
struct ContentView: View {
@State private var bgColor = Color(.sRGB, red: 0.98, green: 0.9, blue: 0.2)
var body: some View {
NavigationView {
ColorPicker("NavigationBar background color", selection: $bgColor)
.navigationBarTitle("Title", displayMode: .large)
.navigationBarColor(self.$bgColor)
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}