Skip to main content

How to use @State inside SwiftUI previews using @Previewable

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to use @State inside SwiftUI previews using @Previewable 관련

SwiftUI by Example

Back to Home

How to use @State inside SwiftUI previews using @Previewable | SwiftUI by Example

How to use @State inside SwiftUI previews using @Previewable

Updated for Xcode 16

Improved in iOS 18

SwiftUI's previews can be used with @State bindings by using the @Previewable macro, which lets us use testing state alongside views such as TextField and Toggle.

For example, this creates a local piece of state and binds it to a textfield:

#Preview {
    @Previewable @State var username = "Anonymous"
    TextField("Enter your name", text: $username)
}

Important

@Previewable must only be used inside #Preview.

The @Previewable macro can be used alongside any SwiftUI property wrapper, including @FocusState and @GestureState.

Similar solutions…
What's the difference between @ObservedObject, @State, and @EnvironmentObject? | SwiftUI by Example

What's the difference between @ObservedObject, @State, and @EnvironmentObject?
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to use @ObservedObject to manage state from external objects | SwiftUI by Example

How to use @ObservedObject to manage state from external objects
How to disable the overlay color for images inside Button and NavigationLink | SwiftUI by Example

How to disable the overlay color for images inside Button and NavigationLink
How to run some code when state changes using onChange() | SwiftUI by Example

How to run some code when state changes using onChange()

이찬희 (MarkiiimarK)
Never Stop Learning.