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
What you could do before and still can do is:
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.
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."