【问题标题】:Can I override the black background color in SwiftUI dark mode?我可以在 SwiftUI 深色模式下覆盖黑色背景颜色吗?
【发布时间】:2021-09-04 20:38:16
【问题描述】:

我正在尝试在 SwiftUI 暗模式下全局(应用程序范围)更改黑色背景颜色,但我找不到这样做的方法,.background(View) 修改后仅更改它应用的视图的背景to,这不是我要找的!

我尝试覆盖UIColor.systemBackground,但实际上似乎没有任何效果!

编辑:这是我现在拥有的和正在寻找的东西的屏幕截图!

【问题讨论】:

  • 只需制作自己的颜色集,然后用它代替UIColor.systemBackground
  • 只是每个屏幕的背景颜色,还是每个视图的背景颜色?
  • @George 我猜的每一个观点!我的意思是屏幕、列表、导航栏等...基本上每个默认使用UIColor.systemBackground 的视图。
  • @AhmedKamal 明暗模式配色方案,还是自定义?例如,您可以使用 .environment(\.colorScheme, .light) 强制使用配色方案
  • @George 不,我不是要更改配色方案,而是要在深色方案中覆盖黑色背景,例如,使用深蓝色背景而不是黑色背景,但是应用范围内,我不想单独为每个视图设置背景!

标签: ios swift swiftui


【解决方案1】:

好吧,我想出了如何达到预期的结果,这就是我所做的。

  1. 使用所需的背景颜色创建颜色集。
  2. 创建一个易于使用的颜色扩展。
extension Color {
    static let systemBackground = Color("Background")
}
  1. 在您的ContentView
init() {
    UINavigationBar.appearance().backgroundColor = UIColor(Color.systemBackground)
    UITableView.appearance().backgroundColor = UIColor(Color.systemBackground)
    UITableViewCell.appearance().backgroundColor = UIColor(Color.systemBackground)
}

var body: some View {
    ZStack {
        Color.systemBackground
            .edgesIgnoringSafeArea(.vertical)

        MyContent()    
    }
}
  1. 然后如果MyContentList
struct MyContent: View {
    var body: some View {
        List {
            ForEach(items) {
                ItemRow($0)
            }
            .listRowBackground(Color.systemBackground)
        }
    }
}

请注意,修改后的.listRowBackground 应用于ForEach,而不是List

  1. 最后,如果MyContentScrollView 或任何其他自定义视图,您可以简单地使用修改后的background

这是最终结果。


正如@swiftpunk 在他的回答中提到的那样,我希望覆盖UIColor.systemBackground,所有视图都会自动选择新颜色,但结果证明它根本没有任何效果。 ?‍♂️

【讨论】:

  • 但是你没有回答问题!您只是将 UI 的背景颜色更改为其他内容!这不是一个有效的答案!
猜你喜欢
  • 1970-01-01
  • 2013-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多