[英]List selection not changing value
I want to change a @State var
variable whenever a row in a list is being selected. I want to change a
@State var
variable whenever a row in a list is being selected. Similar to what didSelectRow
does in UIKit.类似于
didSelectRow
在 UIKit 中所做的。 That means when tapping on "One" the text on the right-hand side should change from "Nothing selected" to "One" .这意味着当点击"One"时,右侧的文本应该从"Nothing selected"变为"One" 。
Here's my current implementation.这是我当前的实现。 However, tapping on a row does nothing at all.
但是,点击一行根本没有任何作用。
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
}
How can I change the text when someone taps a row?当有人点击一行时如何更改文本?
Selection in List
works only if EditMode
is in active state, so you need to handle it manually, something like仅当
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")
}
}
}
and if needed to highlight background than also do it manually.如果需要突出背景而不是手动进行。
You can use Button
inside your List, and then select the Item in their action like this您可以在列表中使用
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.