Newbie in SwiftUI. When I select an item in the List
below, it only triggers onTapGesture
if I press the Text
. If I press outside the Text
but in the "cell" it doesn’t trigger. I would like it to be triggered, how ca I achieve this?
List(viewModel.cities, id: .self, selection: $selection) { city in
VStack {
Text(city)
.frame(maxWidth: .infinity alignment: .leading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.onTapGesture {
if isFocusedFromTextField {
from = city
} else {
to = city
}
}
}
2
Answers
If it is fine to ignore taps on an already selected row, you can use
onChange(of: selection)
.Otherwise, consider using a
Button
as the list rows instead. This still maintains the selectable nature of the list.Add background in the VStack using
.background()
. Because except the text rest of the view area is blank, and blank area not taking tap gesture.