ios 如何检测SwiftUI中colorScheme的更改?

xkrw2x1b  于 2023-05-19  发布在  iOS
关注(0)|答案(2)|浏览(112)

我在SwiftUI中实现了一个TabView,我想检测colorScheme何时更改,因为我实现了一个自定义页面指示器,颜色取决于colorScheme。tabView包含一个名为onAppear()的方法,我在其中调用setUpApariencie(),但如果我在应用程序运行时更改colorScheme,则页面指示器上的更改不起作用。我给你看代码:

}
                .tabViewStyle(.page(indexDisplayMode: .always))
                .indexViewStyle(.page(backgroundDisplayMode: .always))
                
                .frame( height: heigth * 0.4)
                .onAppear(){
                    setupAppearance()
                }
                
                
            }
            
            
        }
        
    }
    
    
}
func setupAppearance() {
    UIPageControl.appearance().currentPageIndicatorTintColor = colorScheme == .light ? .black : .white
    UIPageControl.appearance().pageIndicatorTintColor = UIColor.black.withAlphaComponent(0.2)
}

还有一件事,我不知道为什么AlphaComponent什么也不做。谢谢。

luaexgnf

luaexgnf1#

您可以通过以下方式查看主题的更改:

class AppThemeViewModel: ObservableObject {
    
    @AppStorage("isDarkMode") var isDarkMode: Bool = true                           // also exists in DarkModeViewModifier()
    
}

struct DarkModeViewModifier: ViewModifier {
    @ObservedObject var appThemeViewModel: AppThemeViewModel = AppThemeViewModel()
    
    public func body(content: Content) -> some View {
        content
            .preferredColorScheme(appThemeViewModel.isDarkMode ? .dark : appThemeViewModel.isDarkMode == false ? .light : nil)
    }
}

更多详情请看这里

k0pti3hp

k0pti3hp2#

这应该可以达到目的:

struct MyView: View {
    @Environment(\.colorScheme) var colorScheme
    
    Text("Hello")
    .onChange(of: colorScheme) { newValue in
         print("\(newValue)")
    }
}

相关问题