[英]List selection not changing value
I want to change a @State var
variable whenever a row in a list is being selected. 类似于didSelectRow
在 UIKit 中所做的。 这意味着当点击"One"时,右侧的文本应该从"Nothing selected"变为"One" 。
这是我当前的实现。 但是,点击一行根本没有任何作用。
struct ContentView: View {
@State var items = [Item(id: 1, text: "One"), Item(id: 2, text: "Two"), Item(id: 3, text: "Three")]
@State var selectedItem: Item? = nil
var body: some View {
GeometryReader { geometry in
HStack(alignment: .center) {
List(items, selection: $selectedItem) { item in
Text(item.text)
}
.frame(width: geometry.size.width / 2.5, height: geometry.size.height)
.listStyle(InsetGroupedListStyle())
Text(selectedItem?.text ?? "Nothing selected")
}
}
}
}
struct Item: Identifiable, Hashable {
var id: Int
var text: String
}
当有人点击一行时如何更改文本?
仅当EditMode
处于活动状态 state 时, List
中的选择才有效,因此您需要手动处理它,例如
var body: some View {
GeometryReader { geometry in
HStack(alignment: .center) {
List(items) { item in
Text(item.text)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture {
selectedItem = item
}
}
.frame(width: geometry.size.width / 2.5, height: geometry.size.height)
.listStyle(InsetGroupedListStyle())
Text(selectedItem?.text ?? "Nothing selected")
}
}
}
如果需要突出背景而不是手动进行。
您可以在列表中使用Button
,然后在他们的操作中使用 select 项目,如下所示
List(items, id:\.self, selection: $selectedItem) { item in
Button(action: {
self.selectedItem = item
})
{
Text(item.text)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.