swiftuibindingpreview

SwiftUI #Preview test data


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'


Solution

  • 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()
        }
    }