0

The #Preview macro is frustrating me! Test data that looks obvious to me fails to build. Here is a stripped down example:-

    import SwiftUI

    struct TestView: View {
        @State private var intValue = 0

        var body: some View {
            TestMenuView(intValue: $intValue)
        }
    }

    #Preview {
        TestView()
    }

    struct TestMenuView: View {
        @Binding var intValue: Int

        var body: some View {
            Text("Value passed in was \($intValue)")
        }
    }

    #Preview {
        TestMenuView(intValue: 1)
    }

But the #Preview of TestMenuView gives the error:- Cannot convert value of type 'Int' to expected argument type 'Binding'

2
  • 1
    TestMenuView(intValue: .constant(1)) Commented May 1, 2024 at 7:59
  • Thank you, Joakim, that gets my #Preview working Commented May 2, 2024 at 3:48

1 Answer 1

0

The compiler is telling you that you are trying to initialize the view with an Int type, instead of the expected type Binding<Int>.

You can get around this in a couple of ways.

  1. Initialize it with a constant value like so: TestMenuView(intValue: .constant(1))
  2. Or if you want the preview to be able to display a dynamic value, you can wrap your preview in another view that passes the value from a state.

Replace your #Preview { } with this:

struct TestMenuView_Previews: PreviewProvider {
    struct TestMenuViewContainer: View {
        @State var intValue = 1

        var body: some View {
            TestMenuView(intValue: $intValue)
        }
    }

    static var previews: some View {
        TestMenuViewContainer()
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, Bjorn, both of those answers work. Now that I am starting understand #Preview better, I think I'll be able to deal with the real code for my app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.