Dam*_*zzi 4 list ontouch swift swiftui
我尝试使用 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
}
Run Code Online (Sandbox Code Playgroud)
在此先感谢您的帮助。
虽然您的 Damiano 答案是正确的,但它只能在Text
. 有时需要整行可点击,所以这里是这种情况的解决方案:
List(items) { item in
HStack {
Text(item.icaoAirport).bold()
Spacer()
Text(item.nameAirport)
}
.contentShape(Rectangle())
.onTapGesture {
print("touched item \(item)")
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您仅在HStack
例如的一侧有内容:
HStack {
Text("Some text") // This text will be on the left side
}
Run Code Online (Sandbox Code Playgroud)
那么.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())
Run Code Online (Sandbox Code Playgroud)
我解决了我的问题:
HStack {
Text(item.icaoAirport).bold()
Spacer()
Text(item.nameAirport)
.onTapGesture {
print("touched item \(item.icaoAirport)")
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3266 次 |
最近记录: |