Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI pick a value from a list with ontap gesture

i'm try to pick some value from a swiftUI list with the ontapGesture.

I have a Searchlist of item, the user need to choose one item and then the app will send the choice to an array that later will be use for other info.

now my problem is how do I do that? how can do it? as you can see from the code below, I want to pick the value of the item.icaoAirport corresponding to that raw and pass to an array.

 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

            }

thanks in advance for the help.

like image 422
Damiano Miazzi Avatar asked Oct 22 '19 08:10

Damiano Miazzi


1 Answers

While your, Damiano, answer is right it works only on tap on the Text. Sometimes it is needed to have the whole row tappable, so here is the solution for this case:

List(items) { item in
    HStack {
        Text(item.icaoAirport).bold()
        Spacer()
        Text(item.nameAirport)
    }
    .contentShape(Rectangle())
    .onTapGesture {
        print("touched item \(item)")
    }
}

Thanks Paul for this (https://www.hackingwithswift.com/quick-start/swiftui/how-to-control-the-tappable-area-of-a-view-using-contentshape)

Note, that if you have content only on one side of the HStack e.g:

HStack {
    Text("Some text") // This text will be on the left side
}

then the .contentShape(Rectange()) will work only for the width of the text. So to enable it for the whole width just add a trailing Spacer() like this:

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())
like image 107
ramzesenok Avatar answered Nov 15 '22 06:11

ramzesenok