首页 > 解决方案 > 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

            }

在此先感谢您的帮助。

标签: swiftlistswiftuiontouch

解决方案


虽然您的 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())

推荐阅读