ios - 如何在 SwiftUI 的 List 中设置和使用参数“selection”
问题描述
我已经了解了 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<Set<SelectionValue>>?
and的参数Binding<Set<SelectionValue>>?
。
我已经阅读了如何在 SwiftUI 的列表中启用选择,并且我已经获得了此代码。此代码确实支持多项选择。
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<String>()
……?
有人解释容易理解吗?我会有简单的例子......
非常感谢你,老师!感谢您阅读我的问题!!
解决方案
如何更改为单选列表?
@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]]
}
选择的类型是通过状态变量的类型来检测的,如果设置为多选,如果是可选的,则为单选。
推荐阅读
- java - startAt() 和 endAt() 上的 Firebase orderByChild 返回错误结果
- django-rest-framework - Django中嵌套JSON的序列化
- python - 无法更改 numpy 数组中字符串的大小
- scala - 使用 Scala 连接具有特定数量寄存器的列
- capl - CAPL 测量从睡眠到唤醒 LIN 的时间
- routes - 如何在 Angular 8 中使用 RouterLinkActive?
- python-3.x - 使用熊猫数据框时出现 KeyError
- r - 有效地将高斯噪声添加到矩阵行的每个元素
- javascript - 我无法在 mongodb 服务器中添加第一个用户
- fortran - 用 fortran 编写的 read 语句中的隐含 do 语句