iosswiftswiftuixcode15

How to create a SwiftUI #Preview in Xcode 15 for a view with a @Binding


If I wanted to create a preview for a SwiftUI view that contains a @Binding I would have previously written something like this:

struct SpecialButton_Preview: PreviewProvider {
    static var previews: some View {
        @State var value: Bool = true
        SpecialButton(isOn: $value)
    }
}

However Xcode 15 now comes with a new syntax (#Preview) but when I try to add my example state property, it does not work:

#Preview {  // Error: Ambiguous use of 'Preview(_:traits:body:)'
    @State var value: Bool = true
    SpecialButton(isOn: $value)
}

How can I make this work?


Solution

  • You need to return the View to preview. I'm not exactly sure how this works, it has to do with how Swift macros work.

    #Preview {
        @State var value: Bool = true
        return SpecialButton(isOn: $value)
    }
    

    From the WWDC Slack: "The new #Previews macro simply takes a closure that returns the thing to be previewed. So you can declare local variables or do other setup necessary in there just like you would in any other closure."

    Edit: This only works when you don't want to update the state, otherwise you have to follow the way mentioned by de.

    Updated for Xcode 16:

    New @Previewable macro for using dynamic properties inline in #Preview

    #Preview {
        @Previewable @State var value = true
        SpecialButton(isOn: $value)
    }