Adding a UITapGestureRecognizer
to my UILabel
. I've created a outlet collection
for the UILabels
I want to add the tap event to. Here is my code:
Outlet Collection Name = viewLabels
let removeLabelTapGesture = UITapGestureRecognizer(target: self, action: #selector(removeTagLabel(_:)))
for label in (0..<viewLabels.count) {
viewLabels[label].addGestureRecognizer(removeLabelTapGesture)
}
@objc func removeTagLabel(_ sender: UITapGestureRecognizer) {
print ("inside removeTagLabel")
}
I'm iterating through my outlet collection and adding the gesture recognizer
to each UILabel
. There was nothing being printed in the console.
After hitting my head for a few hours, I thought to try adding the gesture recognizer
individually to each UILabel
.
viewLabels[0].addGestureRecognizer(removeLabelTapGesture)
Now this works for one of the UILabels
. Following this approach, if I do it individually it adds the gesture event
to the last UILabel
that I add the event to.
viewLabels[0].addGestureRecognizer(removeLabelTapGesture)
.
.
.
viewLabels[x].addGestureRecognizer(removeLabelTapGesture) //Will add gesture event to this UILabel
Is there a way to add the gesture recognizer
to each of my UILabels
?
None of your approaches works. The problem is that your code tries to add the very same tap gesture recognizer to all the labels. You can’t do that, just like you yourself can’t be in New York and London at the same time.