Home > Mobile >  Adding GestureRecognizer in loop doesn't work Swift
Adding GestureRecognizer in loop doesn't work Swift

Time:05-26

I am trying to loop through my different views and add gesture recognizers to them. But this does not add the gestures to them:

for i in numberOfViews {
     view.viewWithTag(i)?.addGestureRecognizer(gesture)
}

But when I do it outside of the loop it works:

view.viewWithTag(8)?.addGestureRecognizer(gesture)

I verifed this is true by looping through the gestures added

var listofgest = view.viewWithTag(8)?.gestureRecognizers ?? []
for each in listofgest {
    print("this is a gest \(each)")
}

CodePudding user response:

I'm fairly certain that a gesture recognizer can only be added to a single view. Your code is trying to add the same gesture recognizer, gesture, to all the views in view.viewWithTag(i) (where i is an array of integers?). Don't do that.

Create a separate gesture recognizer for each view that you want to have it's own gesture recognizer.

Otherwise, add the gesture recognizer to the superview. Then it will fire when you tap anywhere on the superview.

  • Related