我正在尝试在我的应用程序中实现一个颜色主题选择器。我要克服的最后一个障碍是动态改变我的UINavigationBar的颜色。目前,我的更改颜色的功能确实有效,但它只有在应用程序从关闭状态重新启动时才会生效。
我的根视图控制器像这样设置UINavigationBar的初始状态:
struct MyRootView: View {
init() {
UINavigationBar.appearance().backgroundColor = getPreferredThemeColour()
UINavigationBar.appearance().largeTitleTextAttributes = [
.foregroundColor: UIColor.white]
}
var body: some View {
...getPreferredThemeColour()只是从UserDefaults返回所需的UIColour
我的主题选择器有一些更改颜色属性的按钮,如下所示:
Button(action: {
UserDefaults.standard.set(UIColor.blue, forKey: "theme")
UINavigationBar.appearance().backgroundColor = UIColor.blue }) {我似乎找不到任何方法来“即时”刷新UINavigationBar以反映所做的更改。应用程序总是需要重新启动。
任何帮助都将非常感谢!谢谢。
发布于 2020-06-17 22:35:26
应用于外观本身之后创建的实例的外观。因此,解决方案是在外观更改后重新创建NavigationView。
这是一个有效的方法演示。使用Xcode11.4/ iOS 13.4进行测试

struct DemoNavigationBarColor: View {
@State private var force = UUID()
init() {
let navBarAppearance = UINavigationBarAppearance()
navBarAppearance.configureWithOpaqueBackground()
navBarAppearance.backgroundColor = UIColor.systemRed
UINavigationBar.appearance().standardAppearance = navBarAppearance
}
var body: some View {
VStack {
NavigationView(){
List(1 ... 20, id: \.self) { item in
NavigationLink(destination:
Text("Details \(item)")
) {
Text("Row \(item)")
}
}
.navigationBarTitle("Title", displayMode: .inline)
}.id(force) // recreate NavigationView
Button("Be Green") {
UINavigationBar.appearance().standardAppearance.backgroundColor = UIColor.systemGreen
self.force = UUID() // << here !!
}
}
}
}https://stackoverflow.com/questions/62430927
复制相似问题