I have implemented a dark/light mode switch in my app using the guide here on this thread. Sample code below:
public struct DarkModeViewModifier: ViewModifier {
@AppStorage("isDarkMode") var isDarkMode: Bool = true
public func body(content: Content) -> some View {
content
.environment(\.colorScheme, isDarkMode ? .dark : .light)
.preferredColorScheme(isDarkMode ? .dark : .light) // tint on status bar
}
}
And to call it:
Picker("Color", selection: $isDarkMode) {
Text("Light").tag(false)
Text("Dark").tag(true)
}
.pickerStyle(SegmentedPickerStyle())
How to implement this with an addition of a System
segment? I thought of setting an Int
as a default setting, but I cannot figure out how to tie it with the @AppStorage
property wrapper.
And also how does watching system mode changes come into effect here in SwiftUI?
Update: In iOS 15, it looks like windows is deprecated. How to update it for iOS 15 in the most sane way? I've seen some other solutions for isKeyWindow, but not sure how to apply it here.
Thanks to @diogo for his solution. I have adapted it for ios 15 into a custom view which could be used in a settings page: