Today, we will see a simple preview trick which will make it easy for you to test your components in dark/light mode.
Our final result will look like this:
We will start with SwiftUI view.
struct DarkLightMode: View {
}
We will add environment property to observe current appearance, using colorScheme keyPath.
struct DarkLightMode: View {
@Environment(\.colorScheme) var colorScheme
}
Inside the body, we will add a ZStack so we can add background to the screen. While we are here, let’s also add a few views and change their appearance based on light/dark mode as shown below.
struct DarkLightMode: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
ZStack {
Color(colorScheme == .dark ? .black : .white).ignoresSafeArea(.all)
VStack {
Text("Here is ")
Text(colorScheme == .dark ? "Dark mode" : "Light mode")
.font(.custom("chalkduster", size: 24))
Button(action: {}) {
Text("Button")
}
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 10))
.clipped()
.shadow(color: .primary, radius: 5, x: 0, y: 0)
}
}
}
}
Now comes the fun part. We will update our preview in such a way where we can display each mode in half of the screen. Have you guessed it yet?
Yesss, we will use a VStack to show our SwiftUI view as shown below:
struct DarkLightMode_Previews: PreviewProvider {
static var previews: some View {
VStack {
DarkLightMode()
.colorScheme(.dark)
DarkLightMode()
.colorScheme(.light)
}
}
}
Complete code:
import SwiftUIstruct DarkLightMode: View {
@Environment(\.colorScheme) var colorScheme
var body: some View {
ZStack {
Color(colorScheme == .dark ? .black : .white)
.ignoresSafeArea(.all)
VStack {
Text("Here is ")
Text(colorScheme == .dark ? "Dark mode" : "Light mode")
.font(.custom("chalkduster", size: 24))
Button(action: {}) {
Text("Button")
}
.padding(.horizontal, 10)
.padding(.vertical, 5)
.background(RoundedRectangle(cornerRadius: 10))
.clipped()
.shadow(color: .primary, radius: 5, x: 0, y: 0)
}
}
}
}struct DarkLightMode_Previews: PreviewProvider {
static var previews: some View {
VStack {
DarkLightMode()
.colorScheme(.dark)
DarkLightMode()
.colorScheme(.light)
}
}
}
With that we have reached the end of this article. Thank you once again for reading. Subscribe to our weekly newsletter at https://www.devtechie.com