1

我想显示一些数据的类别和子类别。我有从 json 获得的数据,当一个类别没有子类别时parent = 0,如果它不为零,则可以理解该类别具有子类别。

然后从护理人员列表中我希望有一个NavigationLink根据 的值parent

我怎样才能NavigationLink有条件?

如果类别没有子类别,则必须转到Product ()视图,否则必须转到Scategory视图

类似的东西,要添加到Navigation Link

if parent == 0 {
Product()
} else {
Scategory()
}

基本示例代码

struct ContentView: View {
    private let cats = [
        "Category 1", "Category 2"
    ]

    //Here I am assuming this value, when changing to zero you must change the destination of `navigationLInk`
    var parent = 20

    var body: some View {
        NavigationView {
            List(cats, id: \.self) { item in
                //Here, how can I add a conditional to the `NavigationLink` using the value of` parent`
                NavigationLink(destination: Scategory(item: item)) {
                    Text(item)
                }
            }.navigationBarTitle("Category")
        }
    }
}

struct Scategory: View {
    let item: String

    var body: some View {
        VStack {
            Text("Subcategory View \(item)")
                .font(.largeTitle)
        }
    }
}


struct Product: View {
    let item: String

    var body: some View {
        VStack {
            Text("Produc View \(item)")
                .font(.largeTitle)
        }
    }
}

意见

4

3 回答 3

0

尝试将您的自定义视图转换成AnyView这样:

if parent == 0 {
    AnyView(Product())
} else {
    AnyView(Scategory())
}
于 2020-02-16T16:08:16.090 回答
0

在 NavigationLink 声明中使用三级运算符:

NavigationLink(destination: self.parent == 0 ?  Product() : Scategory())) {
                Text(String(item))
}
于 2019-11-26T22:43:34.350 回答
0

我应该这样做:

            if self.parent == 0 {

            NavigationLink(destination: Product(item: item)) {
                Text(item)
            }
            } else {

                NavigationLink(destination: Scategory(item: item)) {
                    Text(item)
            }
于 2019-11-26T22:43:34.837 回答