swift - SwiftUI 使用 ontap 手势从列表中选择一个值
问题描述
我正在尝试使用 ontapGesture 从 swiftUI 列表中选择一些值。
我有一个项目的搜索列表,用户需要选择一个项目,然后应用程序会将选择发送到稍后将用于其他信息的数组。
现在我的问题是我该怎么做?怎么办?正如您从下面的代码中看到的那样,我想选择与该 raw 对应的 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())
推荐阅读
- javascript - 我希望 angular 4 ng2-ui/map places-auto-complete 仅限于特定国家
- php - 使用 $_GET 将变量传递给多个页面
- html - 在主 div 中居中 div 和内容
- jenkins - Jenkins 动态流水线参数
- sql - 使用查询查找范围内的日期
- javascript - AnalyserNode.getFloatFrequencyData 总是返回 -Infinity
- node.js - 在 heroku 中部署 angular/Nodejs 应用程序
- jersey - 使用 Keycloak 4.3.0.Final 和 dropwizard 1.3.1
- c# - 你调用的对象是空的。- 抱歉,我无法理解其他发布类似内容的人
- python - 为什么在 python 中非常大的浮点值之间的比较会失败?