Some discussion on gestureRecognizers

I would appreciate some feedback on this simple technical point.

When a gesture is defined in code, it is simply added to the view with

        myFirstView.addGestureRecognizer(someGesture)

That's fine.

But, if by mistake, the same gesture is added later to another view

        myOtherView.addGestureRecognizer(someGesture)

myFirstView will not receive anymore the notification.

That's well known and documented, because in fact the gesture references the view and can only reference one.

So my point:

  • this may be a bit misleading, as API let one believe that the gesture is attached to the view ; hence, why not attach to a second view ?
  • wouldn't it be better to have API where view is explicitly "attached" to gesture ?
        someGesture.attach(to: myFirstView)

Doing so, if I later

        someGesture.attach(to: myOtherView)

it would be clearer I am changing the attached view.

  • I noted that when we define a gesture in IB, we can only connect from the view to the gesture, not from gesture to the view which seems to follow the same logic.

A simple extension does it:

extension UITapGestureRecognizer {
    
    func attach(to view: UIView) {
        view.addGestureRecognizer(self)
    }
}

Any thought ?

PS: I'm amazed by code completion.

I just typed

extension UITapGestureRecognizer {
    func attach(to view: UIView)

and it completed automatically the code with

        view.addGestureRecognizer(self)
Some discussion on gestureRecognizers
 
 
Q