ios - SwiftUI - 动态刷新 UINavigationBar.appearance().backgroundColor
问题描述
我正在尝试在我的应用程序中实现颜色主题选择器。我要克服的最后一个障碍是动态更改 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 以反映所做的更改。该应用程序始终需要重新启动。
任何帮助将不胜感激!!!!谢谢你。
解决方案
外观应用于在外观本身之后创建的实例。NavigationView
所以解决方案是在外观改变后重新创建。
这是一个有效的方法演示。使用 Xcode 11.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 !!
}
}
}
}
推荐阅读
- amazon-eks - 无法在 EKS 集群上创建 PodPreset
- javascript - elementsFromPoint 不包含 mouseover 元素
- ssl - AWS 应用程序负载均衡器上的 Websocket + SSL
- php - PHP:为什么只能通过引用传递变量?
- javafx - 如何在超链接单击时获取 tableview 项目
- postgresql - Postgres LIKE %% 语法错误
- spring - 我如何知道 SSL 证书链正在被验证?
- r - 使用 R 包中的 `/exec` 目录用于 R 脚本以进行可重复的研究
- webpack - 为什么 webpack 的事件监听器钩子叫做 `plugin` 而不是 `on` 之类的?
- gmail - 是否可以链接到 GMail 委托帐户中的电子邮件