Adjust SwiftUI view’s background color for dark mode
In this tutorial, we’ll explore how to dynamically change the background color of a view based on the system’s dark mode setting.
Dark mode is a popular feature for experiencing a more comfortable interface in low-light conditions. In SwiftUI, we can easily make our app change its appearance based on whether the user prefers light or dark mode.
Using the default system background color
If you want to use the default background color provided by the system, which automatically adapts to light or dark mode, then simply implement UIColor.systemBackground
within the background()
modifier.
Syntax:
.background(Color(UIColor.systemBackground))
In the above code, I have implemented the background(Color(UIColor.systemBackground))
to automatically adjust the background color based on the current light or dark mode setting.
Example
import SwiftUI struct ContentView: View { var body: some View { Text("WELCOME TO CODESPEEDY") // To adjust the background color based on light/dark mode .background(Color(UIColor.systemBackground)) } }
Output:
Customizing the color
If you want more control over the background color and prefer to customize it yourself based on light or dark mode, you can use the .colorScheme
environment variable.
@Environment(\.colorScheme) var colorScheme
The above code will access the color scheme environment variable, which indicates whether the device is in light or dark mode.
Example
import SwiftUI struct ContentView: View { // Declare a property to access the color scheme environment variable @Environment(\.colorScheme) var colorScheme var body: some View { Text("WELCOME TO CODESPEEDY") // Set the background color based on light/dark mode .background(colorScheme == .dark ? Color.mint : Color.white) } }
In the above program, within the background()
modifier, I have set the background color of the view based on the value of the colorScheme
property.
So, if the system is in dark mood ( colorScheme == .dark
), the background color will be black ( Color.black
). Otherwise, the background color will be white ( Color.white
).
Output:
Leave a Reply