One of the most revolutionary features of SwiftUI is the Canvas Preview in Xcode.
It allows you to see your UI changes rendered instantly, without waiting for the app to compile and launch in the simulator.
To make this work, Xcode relies on special Preview blocks at the bottom of your SwiftUI files.
#Preview MacroIn modern versions of Xcode (Xcode 15+), generating a preview is as simple as using the #Preview macro.
You simply attach this macro to a block of code returning the View you want to see.
import SwiftUIstruct UserProfileView: View { var body: some View { Text("Akash's Profile") .font(.title) } }
// This block tells Xcode what to render on the Canvas #Preview { UserProfileView() }
When you run your actual app, the compiler automatically ignores #Preview blocks, so they don't bloat your production code!
If your view requires data (like a user object) to render, you must provide "mock data" directly inside the preview block.
This allows you to test how your UI looks with extremely long names, empty states, or error conditions.
struct ArticleCard: View {
let title: String
var body: some View {
Text(title).bold()
}
}
#Preview("Short Title") {
ArticleCard(title: "Swift Basics")
}
#Preview("Long Title") {
ArticleCard(title: "An extremely long title that might cause layout issues!")
}
By providing a string to the #Preview macro, you can create multiple tabs in your Xcode canvas to test different scenarios simultaneously.
You can attach modifiers to the View inside the #Preview block to simulate different device states.
For instance, you can easily check what your view looks like in Dark Mode!
#Preview("Dark Mode Test") {
UserProfileView()
.preferredColorScheme(.dark)
}
You can also test different Dynamic Type (font) sizes and different device orientations.
Which modern Swift macro is used to generate the interactive Canvas preview in Xcode?