skip to Main Content

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?

2

Answers


  1. What you could do before and still can do is:

    SpecialButton(isOn: .constant(true))
    
    Login or Signup to reply.
  2. 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."

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search