简体   繁体   English

SwiftUI 使用 NavigationLink 列表多选

[英]SwiftUI list multiselect with NavigationLink

In SwiftUI running on macOS, for a list of items where each item in the list is a NavigationLink, multi-selection does not work.在 macOS 上运行的 SwiftUI 中,对于列表中的每个项目都是 NavigationLink 的项目列表,多选不起作用。 If the exact same view does not include the NavigationLink it works fine.如果完全相同的视图包含 NavigationLink,则它工作正常。 How can I have both multi-selection and NavigationLink in the same list running on macOS?如何在 macOS 上运行的同一个列表中同时拥有多选NavigationLink? Perhaps this requires a different method of constructing NavigationLinks that isn't tied to the list?也许这需要一种不同的方法来构建不依赖于列表的 NavigationLinks? Is that even possible?这可能吗? I've tried conditionally disabling the NavigationLink when multiple rows are selected, but this has no effect (eg .disabled(selection.count > 1) ).我试过在选择多行时有条件地禁用 NavigationLink,但这没有效果(例如.disabled(selection.count > 1) )。

Example where multi-select does not work (notice in the screenshot when three results are shift-clicked the full selection shows up briefly and then snaps to the last clicked item):多选不起作用的示例(注意在屏幕截图中,当按住 Shift 键并单击三个结果时,会短暂显示完整选择,然后捕捉到最后单击的项目):

struct TestListView: View {
  @State var selection = Set<String>()
  let options = ["a", "b", "c"]

  var body: some View {
    NavigationView {
      List(options, id: \.self, selection: $selection) { item in
        NavigationLink {
          Text(String(describing: selection))
        } label: {
          Text(item)
        }
      }
    }
  }
}

上面代码的截屏

Example where multi-select works fine:多选工作正常的示例:

struct TestListView: View {
  @State var selection = Set<String>()
  let options = ["a", "b", "c"]

  var body: some View {
    NavigationView {
      List(options, id: \.self, selection: $selection) { item in
        Text(item)
      }
      Text(String(describing: selection))
    }
  }
}

在此处输入图像描述

Looks like I more or less had it in one of the question examples.看起来我或多或少在其中一个问题示例中有过。 A separate bug in a more complex example misled me.一个更复杂的例子中的一个单独的错误误导了我。 Solution is effectively the second option above.解决方案实际上是上面的第二个选项。

In other words, don't try to mix NavigationLink and multi-selection .换句话说,不要尝试混合使用 NavigationLink 和 multi-selection Instead skip the NavigationLink and put the destination view next to the List (only tested on macOS).而是跳过 NavigationLink 并将目标视图放在列表旁边(仅在 macOS 上测试过)。

struct TestListView: View {
  @State var selection = Set<String>()
  let options = ["a", "b", "c"]

  var body: some View {
    NavigationView {
      List(options, id: \.self, selection: $selection) { item in
        Text(item)
      }
      if selection.isEmpty {
        Text("Empty")
      } else if selection.count > 1 {
        Text("Multiple")
      } else if let selection = selection.first {
        Text(selection)
      }
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM