Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass type Namespace.ID in preview parameter in SwiftUI?

Tags:

swiftui

I am creating a subview in SwiftUI with few parameters. One of the parameters' type is Namspace.ID. So I have to pass the Namespace.ID type parameter through preview to see the view in Xcode canvas. I don't know how to do it. My codes look like this.

    struct BagView: View {
        var bagData:BagModel
        var animation:Namespace.ID
        var body: some View {
            VStack{
                ZStack{
                    Color(bagData.image)
                        .cornerRadius(15)
                    Image(bagData.image)
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .padding(20)
                        .matchedGeometryEffect(id: bagData.image, in: animation)
                }
                Text(bagData.title)
                    .fontWeight(.heavy)
                    .foregroundColor(.gray)
                Text(bagData.price)
                    .fontWeight(.heavy)
                    .foregroundColor(.black)
            }
        }
    }
    
    struct BagView_Previews: PreviewProvider {
        static var previews: some View {
            BagView(bagData: BagModel(image: "bag1", title: "The Bag", price: "$123")) 
// I am getting an error here: Missing argument for parameter 'animation' in call
        }
    }

How can I see the view in Canvas by resolving the error?

like image 259
Tanvirgeek Avatar asked Dec 22 '22 16:12

Tanvirgeek


2 Answers

The error tells you, that you forgot a parameter, since animation is a required and non-optional field. So you need to add a value for the property "animation". Something like that:

BagView(bagData: BagModel(...), animation: <valueHere>)

EDIT: You should be able to inject a Namespace value doing the following:

struct BagView_Previews: PreviewProvider {
    @Namespace static var namespace // <- This

    static var previews: some View {
        BagView(bagData: BagModel(image: "bag1", title: "The Bag", price: "$123"), animation: namespace) 
    }
}
like image 94
fusion Avatar answered Feb 20 '23 05:02

fusion


Here is possible approach - use intermediate test/preview view:

struct BagView_Previews: PreviewProvider {
    struct TestView: View {
        @Namespace var ns
        var body: some View {
            BagView(bagData: BagModel(image: "bag1", title: "The Bag", price: "$123"), 
                    animation: ns)
        }
    }
    static var previews: some View {
        TestView()
    }
}
like image 41
Asperi Avatar answered Feb 20 '23 05:02

Asperi