Dark_Mode
Dark Mode
Checking User Style
switch UIScreen.main.traitCollection.userInterfaceStyle {
case .light: //light mode
case .dark: //dark mode
case .unspecified: //the user interface style is not specified
}
Override the App user style
You could use User Defaults to save the in app settings for different themes.
Xcode assets
Utilize Color Set in Xcode with “Any” & “Dark” Mode. To better update the application with dynamic settings.
Dynamic colors
swiftbysundell | dynamic-colors-in-swift/
Detect UI Appearance Change
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
callCustomFunc()
}
}
SO | iOS 13 tableview cell dark mode
SO | iOS 13 detect dark mode changes
Single View Override
First retrieve color scheme of the app.
SwiftUI
Specific single view passed with environment or
.environment(\.colorScheme, .light) // or .dark
// OR
.preferredColorScheme(.dark)
Entire App Color scheme
UIKit
Each UIView
has access to the window, So you can use it to set the . overrideUserInterfaceStyle
value to any scheme you need.
myView.window?.overrideUserInterfaceStyle = .dark
SwiftUI
Copied from StackOverflow post
First you need to access the window to change the app colorScheme that called UserInterfaceStyle
in UIKit
.
I used this in SceneDelegate
:
private(set) static var shared: SceneDelegate?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
Self.shared = self
...
}
Then you need to bind an action to the toggle. So you need a model for it.
struct ToggleModel {
var isDark: Bool = true {
didSet {
SceneDelegate.shared?.window!.overrideUserInterfaceStyle = isDark ? .dark : .light
}
}
}
At last, you just need to toggle the switch:
struct ContentView: View {
@State var model = ToggleModel()
var body: some View {
Toggle(isOn: $model.isDark) {
Text("is Dark")
}
}
}
Resources
Full guide:
apple doc | UI Appearance dark mode interface