SwiftUI可编程更改颜色主题

5
我有 .light 和 .dark 主题。
在预览中(MyContainer_Previews),我可以通过以下方式进行更改:
ForEach([.light,.dark], id: \.self) { theme in

            Group {
                ...
            } 
            .environment(\.colorScheme, theme) //This line
        }
 ...

我如何在应用程序中更改主题(例如按钮操作)。

我试图在SceneDelegate中进行更改:

 let contentView = ContentView()
 contentView.environment(\.colorScheme, .dark) //Not work

方案不是由iPhone用户控制的吗? - E.Coms
我需要覆盖它。如果用户想要始终使用暗色或亮色。 - Tim
我已经回答了你的问题。 - E.Coms
3个回答

8

响应式:

    return NavigationView {
        VStack(alignment: .trailing, spacing: 0) {
            ...
        }

    } 
    .environment(\.colorScheme, appState.options.theme == .light ? .light : .dark)

如果我不想让我的视图在导航视图中,该怎么办? - Peter Schorn

2

有人告诉我,如果您将代码放入NavigationView中,则可以使用enviorment更改方案。

var body: some View {


NavigationView{
   //Your view here
}}

let contentView = ContentView() contentView.environment(\.colorScheme, .dark) //现在可以使用了

  UIHostingController(rootView: ContentView().environment(\.colorScheme, .light)

  struct ContentView: View {
var body: some View {
   NavigationView{
       Text("!")
    }}}

0

我曾经遇到过类似的问题,这段代码对我来说似乎有效。

ForEach([.light,.dark], id: .self) { theme in

        Group {
            ...
        } 
        .preferredColorScheme(theme)
    }

...


你的答案可以通过提供更多支持信息来改进。请[编辑]以添加进一步细节,如引用或文档,以便他人可以确认你的答案是否正确。您可以在帮助中心中找到有关编写良好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接