I am creating a SearchBar right now that gets data from API, the Text highlighted in red ( see image below) is what I want to pass into my userDefault string on tap . This is working as long as I tap the highlighted red text, is it possible to get that value when you tap anywhere in that row like say the white space ? any suggestions would be great .
@State var model: [SearchModel]
var defaults = UserDefaults.standard
@State var isOpen: Bool = false
Above is my State variables and my user default . I won't show the whole code since the issue is only with the below . As you can see my values are in the foreach I just want to have it so that if a user clicks on the white space of the row that I can still execute this code .
.onTapGesture {
isOpen = true
// I set the value here
defaults.setValue(value.name, forKey: "location")
}.fullScreenCover(isPresented: $isOpen, content: MainView.init)
The code above gives me the correct value but it's tied to the Text
ZStack {
Color(UIColor.white)
.ignoresSafeArea()
ScrollView(showsIndicators: false) {
LazyVStack {
ForEach(model) { value in
VStack(alignment: .leading) {
HStack {
Text(value.name)
.font(.system(size: 15))
.background(Color.red)
.padding(.trailing, 10.0)
.onTapGesture {
isOpen = true
// I set the value here
defaults.setValue(value.name, forKey: "location")
}.fullScreenCover(isPresented: $isOpen, content: MainView.init)
}
HStack {
Text(value.statelong)
.foregroundColor(Color.gray)
.font(.system(size: 13))
Spacer()
}
}
VStack {
Spacer()
Divider()
}
}
}.padding(.leading, 20.0)
}
}
.listRowInsets(.none)
It only works for the highlighted text because the
onTapGesture
is on the Text view.1. Using a
HStack()
I would embed the
VStack
in aHStack
and add aSpacer()
to fill the entire area, then place theonTapGesture
to theHStack
, like this:2. Using a
ZStack()
Or you could use a
ZStack
to make a full view background and place the onTapGesture on theZStack
, add.frame(maxWidth: .infinity)
to theZStack
to fill the entire available width, like this: