【问题标题】:NavigationLink with conditional in a List列表中带有条件的 NavigationLink
【发布时间】:2019-11-26 22:30:06
【问题描述】:

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

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

我怎样才能让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)
        }
    }
}

【问题讨论】:

    标签: swift swiftui swiftui-list


    【解决方案1】:

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

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

    【讨论】:

    • 我收到以下错误:Result values in '? :' expression have mismatching types 'Product' and 'Scategory'
    • 将它们包装在 AnyView 中
    【解决方案2】:

    我应该处理这个:

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

    【讨论】:

      【解决方案3】:

      尝试将您的自定义视图转换为AnyView,如下所示:

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

      【讨论】:

        猜你喜欢
        • 2020-07-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 2020-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多