我尝试使用 ontapGesture 从 swiftUI 列表中选取一些值。
我有一个项目搜索列表,用户需要选择一个项目,然后应用会将选择发送到一个数组,稍后将用于其他信息。
现在我的问题是我该怎么做?怎么办? 正如您从下面的代码中看到的那样,我想选择与该原始文件对应的 item.icaoAirport 的值并传递给一个数组。
List(dm.vettoreAeroporti.filter{
// $0.icaoCode.contains(searchTerm)
$0.icaoAirport.localizedCaseInsensitiveContains(searchTerm)
}) { item in
HStack {
Text(item.icaoAirport).bold()
Spacer()
Text(item.nameAirport)
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
self.dm.openFileJson(fileName: "data")
}
}
.onTapGesture {
// ?? I need to take the value of the item.icaoAirport corresponding to that raw
}
在此先感谢您的帮助。
最佳答案
Damiano,虽然你的答案是正确的,但它只能在点击 Text
时起作用。
有时需要让整行都可以点击,所以这里是针对这种情况的解决方案:
List(items) { item in
HStack {
Text(item.icaoAirport).bold()
Spacer()
Text(item.nameAirport)
}
.contentShape(Rectangle())
.onTapGesture {
print("touched item \(item)")
}
}
请注意,如果您只有 HStack
的一侧有内容,例如:
HStack {
Text("Some text") // This text will be on the left side
}
那么 .contentShape(Rectange())
将仅适用于文本的宽度。因此,要为整个宽度启用它,只需添加一个尾随 Spacer()
,如下所示:
HStack {
Text("Some text")
Spacer() // This will take all the space from the end of the text up to the end of the whole row
}
.contentShape(Rectangle())
关于SwiftUI 使用 ontap 手势从列表中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58500295/