首页 > 解决方案 > 如何在 SwiftUI 的预览参数中传递类型 Namespace.ID?

问题描述

我在 SwiftUI 中创建一个带有少量参数的子视图。其中一个参数的类型是 Namspace.ID。所以我必须通过预览传递 Namespace.ID 类型参数才能在 Xcode 画布中看到视图。我不知道该怎么做。我的代码看起来像这样。

    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
        }
    }

如何通过解决错误来查看 Canvas 中的视图?

标签: swiftui

解决方案


该错误告诉您,您忘记了一个参数,因为动画是一个必需且非可选的字段。所以你需要为属性“动画”添加一个值。像这样的东西:

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

编辑:您应该能够执行以下操作注入命名空间值:

struct BagView_Previews: PreviewProvider {
    @Namespace static var namespace
    static var previews: some View {
        BagView(bagData: BagModel(image: "bag1", title: "The Bag", price: "$123"), animation: namespace) 
    }
}

推荐阅读