在我的项目中,我有两个颜色选择器,用于更改背景颜色和字体颜色。
Sheet,我在其中更改颜色:
@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中;当我再次启动应用程序时,更改会显示在导航栏中。
发布于 2020-11-08 18:12:01
声明一个到Color对象的绑定,而不是在ViewModifier中使用普通变量。然后,如果您的包封值发生变化,视图(在本例中是NavigationBar)将自动重新绘制。
我的工作示例:
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()
}
}https://stackoverflow.com/questions/64736556
复制相似问题