Preview SwiftUI views with bindings using @Previewable
Xcode 16 introduced the Previewable macro, making it easier to preview SwiftUI views with bindings. By annotating dynamic properties like @State
in a #Preview
body with @Previewable
, we can pass them as bindings to views directly.
Here is an example on how we can easily setup a fully interactive preview for a basic counter view that accepts a binding:
struct CounterView: View {
@Binding var count: Int
var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment count") {
count += 1
}
}
}
}
#Preview {
@Previewable @State var count = 0
CounterView(count: $count)
}
This example creates an interactive preview where the count value can be updated in real-time using the provided button.
@Previewable
is supported on iOS 17, macOS 14, and other platforms.
If you have older iOS apps and want to enhance them with modern SwiftUI features, check out my book Integrating SwiftUI into UIKit Apps. It provides detailed guidance on gradually adopting SwiftUI in your UIKit projects and was recently updated for iOS 18 and Xcode 16. Additionally, if you're eager to enhance your Swift programming skills, my latest book Swift Gems offers over a hundred advanced tips and techniques, including optimizing collections, handling strings, mastering asynchronous programming, and debugging, to take your Swift code to the next level.