Setup:
Swift 5.5, Xcode 13.2
This topic is all over the web and here's one of them. Well, my app has three options:
- On: Use dark mode no matter what the system is set to
- Off: Use light mode no matter what the system is set to
- System: Use the system defaults (Light or Dark)
I have a simple class that toggles the three:
import SwiftUI
class Utilities: ObservableObject {
// The default is to use the system's default.
@AppStorage("theme") var theme: String = ""
var userInterfaceStyle: ColorScheme? = .dark
func overrideDisplayMode() {
var userInterfaceStyle: UIUserInterfaceStyle
if theme == "On" {
userInterfaceStyle = .dark
} else if theme == "Off" {
userInterfaceStyle = .light
} else {
// System
userInterfaceStyle = .unspecified
}
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.overrideUserInterfaceStyle = userInterfaceStyle
}
}
How it's updated (minus the button function etc):
@main
struct MainApp: App {
@StateObject var utilities = Utilities()
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: utilities.theme, perform: { _ in
utilities.overrideDisplayMode()
})
// Ensures the theme is set when app first loads
.onAppear(perform: {
utilities.overrideDisplayMode()
}
}
}
}
This works well: theming. The only issue is the status bar. I'd like to change the status bar colour whenever I overrideUserInterfaceStyle
or whenever theme
is changed. How can I achieve this with this setup?