iOS adding tapGesture to multiple Views

前端 未结 6 1015
无人及你
无人及你 2020-12-31 03:11

I have multiple views defined in my main view. I want to add single tap gesture to all these views. Below is the code I have written, but this registers a tap gesture to the

6条回答
  •  难免孤独
    2020-12-31 03:49

    1. Can you attach a UIGestureRecognizer to multiple views? No.

    2. Two options:

      a) Give every UIGestureRecognizer its own action. Pluses of this approach: strong decoupling. Minuses: more code reuse. But, you can mitigate code reuse by creating methods for common functionalities and just call the methods in the different actions.

      b) Give every view to which you add a UIGestureRecognizer a unique tag. Then, use a switch statement in the common action with the sender's view's tag as the case. Pluses: less code reuse. Minuses: tighter coupling. Something like this:

      UIGestureRecognizer *singleTap = [[UIGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapAction:)];
      [feedsView addGestureRecognizer:singleTap];
      feedsView.tag = 33;
      

      Then:

      - (void)singleTapAction:(UIGestureRecognizer *)singleTap {
          UIView *view = singleTap.view;
          switch (view.tag) {
              case 33
                  // view is feedsView
                  break;
      
              default:
                  break;
          }
      }
      

      Although it's usually best to go with the option that decouples, if all of your actions are very similar, which seems to be the case here, and you are quite sure that they'll remain very similar in the future, then option b) with the tags is probably the better choice.

    P.S. It's unnecessary to explicitly set numberOfTapsRequired & numberOfTouchesRequired to 1 since they're both set to 1 by default. You can confirm this by holding Command and clicking on numberOfTapsRequired in Xcode.

提交回复
热议问题