SwiftUI列表选择没有价值

时间:2020-10-10 07:39:21

标签: ios swift swiftui

我想基本上像在SwiftUI中使didSelectRowUITableView一样。

这是代码:

struct ContentView: View {

    var testData = [Foo(name: "1"),
                Foo(name: "2"),
                Foo(name: "3"),
                Foo(name: "4"),
                Foo(name: "5")]

    @State var selected: Foo?

    var body: some View {

        NavigationView {
        VStack {
            List(testData, id: \.name, selection: $selected) { foo in
                HStack {
                    Text(foo.name)

                }
            }.navigationBarTitle("Selected \(selected?.name ?? "")")
            Button("Check:") {
                print(selected?.name)
            }
        }

    }
}

我曾经想过,如果单击单元格,那么selected应该包含所选值,但不是。 selected没有任何价值。而且该单元格不可点击。

所以我添加了Button

NavigationView {
        VStack {
            List(testData, id: \.name, selection: $selected) { foo in
                HStack {
                    Text(foo.name)
                    Button("Test") {
                        print("\(foo) is selected.")
                        print(selected?.name)
                    }
                }
            }.navigationBarTitle("Selected \(selected?.name ?? "")")
            Button("Check:") {
                print(selected?.name)
            }
        }

现在,单击有效了,但实际上foo是我想要的,selected selection中的List为何在这里。

不确定我错过了什么。 Button对“ List”来说是否需要didSelectRow?谢谢!

编辑

经过更多调查,我目前的结论是:

  • 对于单个选择,无需致电List(.. selection:)。但是您必须使用ButtonOnTapGesture来实现可点击。
  • List(.. selection:)仅适用于编辑模式,它是多项选择,如您所见selection:需要一组。我的例子应该是 @State var selected: Set<Foo>?

1 个答案:

答案 0 :(得分:0)

在iOS上,按设计选择的内容在“编辑”模式下有效

    /// Creates a list with the given content that supports selecting multiple
    /// rows.
    ///
>>    /// On iOS and tvOS, you must explicitly put the list into edit mode for
>>    /// the selection to apply.
    ///
    /// - Parameters:
    ///   - selection: A binding to a set that identifies selected rows.
    ///   - content: The content of the list.
    @available(watchOS, unavailable)
    public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content)

因此您需要在某处添加EditButton,或以编程方式激活编辑模式,例如

List(selection: $selection) {
   // ... other code
}
.environment(\.editMode, .constant(.active))   // eg. persistent edit mode

更新:这是默认SwiftUI列表选择的一些演示

demo

struct DemoView: View {
    @State private var selection: Set<Int>?
    @State private var numbers = [0,1,2,3,4,5,6,7,8,9]
    var body: some View {
        List(selection: $selection) {
            ForEach(numbers, id: \.self) { number in
                VStack {
                    Text("\(number)")
                }
            }.onDelete(perform: {_ in})
        }
        .environment(\.editMode, .constant(.active))
    }
}
相关问题