列表中有条件的NavigationLink

时间:2019-11-26 22:30:06

标签: swift swiftui swiftui-list

我想显示一些数据的类别和子类别。我有从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)
        }
    }
}

Views

3 个答案:

答案 0 :(得分:0)

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

NavigationLink(destination: self.parent == 0 ?  Product() : Scategory())) {
                Text(String(item))
}

答案 1 :(得分:0)

我应该处理这个问题

            if self.parent == 0 {

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

                NavigationLink(destination: Scategory(item: item)) {
                    Text(item)
            }

答案 2 :(得分:0)

尝试像这样将您的自定义视图投射到if parent == 0 { AnyView(Product()) } else { AnyView(Scategory()) } 中:

function tbot(){
  while (turn == "player 2") {
    if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    ) {t4()}

    else {
    var tiles = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
    var tile = tiles[Math.floor(Math.random()*tiles.length)];
         if (tile == '0' && t01 == 0) {t0()}
    else if (tile == '1' && t11 == 0) {t1()}
    else if (tile == '2' && t21 == 0) {t2()}
    else if (tile == '3' && t31 == 0) {t3()}
    else if (tile == '4' && t41 == 0) {t4()}
    else if (tile == '5' && t51 == 0) {t5()}
    else if (tile == '6' && t61 == 0) {t6()}
    else if (tile == '7' && t71 == 0) {t7()}
    else if (tile == '8' && t81 == 0) {t8()}
  }
  }
}