【问题标题】:How can I set and use the argument "selection" in List in SwiftUI如何在 SwiftUI 的 List 中设置和使用参数“selection”
【发布时间】:2020-08-09 08:29:13
【问题描述】:

我了解了 SwiftUI,但在 SwiftUI 中理解 List 有困难。

列表定义如下。

@available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
public struct List<SelectionValue, Content> : View where SelectionValue : Hashable, Content : View {

    /// Creates a List that supports multiple selection.
    ///
    /// - Parameter selection: A binding to a set that identifies the selected
    ///   rows.
    ///
    /// - See Also: `View.selectionValue` which gives an identifier to the rows.
    ///
    /// - Note: On iOS and tvOS, you must explicitly put the `List` into Edit
    ///   Mode for the selection to apply.
    @available(watchOS, unavailable)
    public init(selection: Binding<Set<SelectionValue>>?, @ViewBuilder content: () -> Content)

    /// Creates a List that supports optional single selection.
    ///
    /// - Parameter selection: A binding to the optionally selected row.
    ///
    /// - See Also: `View.selectionValue` which gives an identifier to the rows.
    ///
    /// - Note: On iOS and tvOS, you must explicitly put the `List` into Edit
    ///   Mode for the selection to apply.
    @available(watchOS, unavailable)
    public init(selection: Binding<SelectionValue?>?, @ViewBuilder content: () -> Content)

    :
    :

}

那么我的问题是,我怎样才能拥有支持多选/单选的列表? 我会知道如何设置Binding&lt;Set&lt;SelectionValue&gt;&gt;?Binding&lt;Set&lt;SelectionValue&gt;&gt;? 的参数。

我已经阅读了How does one enable selections in SwiftUI's List,并且得到了这段代码。此代码确实支持多选。

var demoData = ["Phil Swanson", "Karen Gibbons", "Grant Kilman", "Wanda Green"]

struct ContentView: View {
    @State var selectKeeper = Set<String>()

    var body: some View {
        NavigationView {
            List(demoData, id: \.self, selection: $selectKeeper){ name in
                Text(name)
            }
            .navigationBarItems(trailing: EditButton())
            .navigationBarTitle(Text("Selection Demo \(selectKeeper.count)"))
        }
    }
}

但我仍然无法理解如何设置参数“选择”并设置类型。如何更改为单选列表?什么是Set&lt;String&gt;()...?

有没有人解释得通俗易懂? 我会举个简单的例子...

非常感谢,老师!感谢您阅读我的问题!

【问题讨论】:

    标签: ios swift list swiftui swift5


    【解决方案1】:

    如何更改为单选列表?

    @State var selectKeeper: String? = nil // << default, no selection
    

    什么是 Set()...?

    所选项目的容器,在您的情况下是来自demoData的字符串

    如何设置参数“选择”并设置类型

    一个变体在.onAppear 中,如下所示

    List(demoData, id: \.self, selection: $selectKeeper){ name in
        Text(name)
    }
    .onAppear {
       self.selectKeeper = [demoData[0]]
    }
    

    选择的类型通过状态变量的类型来检测,如果设置为多选,如果是可选的,则单选。

    【讨论】:

    • Asperi-san,感谢您提供通俗易懂的回答!我很感激老师:)我可以得到我想要的所有信息。
    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2019-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    相关资源
    最近更新 更多