如何在 SwiftUI 的预览参数中传递类型 Namespace.ID?

Tan*_*eek 3 swiftui

我正在 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
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

小智 14

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

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

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

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) 
    }
}
Run Code Online (Sandbox Code Playgroud)


Gag*_*iOS 6

迟到的答案,但我在下面找到了另一个选项(我来这里是为了搜索命名空间)

添加 命名空间().wrappedValue

例子: -

struct TabItemView_Previews: PreviewProvider {
    static var previews: some View {
        TabItemView(tintColor: .blue, inActiveColor: .gray, tab: .home, tabAnimation: Namespace().wrappedValue, activeTab: .constant(.home))
    }
}
Run Code Online (Sandbox Code Playgroud)


Asp*_*eri 5

这是可能的方法 - 使用中间测试/预览视图:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)