SwiftUI 使用 ontap 手势从列表中选择一个值

标签 swift list swiftui ontouch

我尝试使用 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)")
    }
}

感谢保罗 (https://www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape)

请注意,如果您只有 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/

相关文章:

ios - 将我的帐户中的 Google 日历集成到 iOS 应用程序中

python - 在另一个defaultdict(树)中动态创建defaultdict(列表)

查找列表中出现次数最少的对象的 Pythonic 方法

ios - SwiftUI 列表未更新内拉以刷新 View

ios - SwiftUI 中 UICollectionViewController 的替代品是什么?

swift - 在 SwiftUI 中启用 ScrollView over scroll

Swift UIButton BarButtonItem 中图像大小扭曲

ios - 表格 View 中的 SWIFT 数据未显示

ios7 - 从字典中获取任何对象

Python - 将字典列表拆分为单独的字典