Issue with a UITapGestureRecognizer

本秂侑毒 提交于 2019-11-28 03:39:48

问题


I have a main viewController, it is called WelcomeViewController. I have a UIView subclass and that has some view related stuff in it. I want to add a UITapGestureRecognizer to that subclass. I only want the gesture recognizer to acknowledge taps inside that subview. How do I do that. Should I put the UITapGestureRecognizer in the subclass or should I put it in the Welcome vc. Thanks in advance.

Also, I have played around with it a bunch and can't seem to figure it out.


回答1:


It depends on whether you want to handle the tap in your custom view object or in the view controller.

If in the view, add this to it's init or other proper place:

UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:tapRecognizer];
[tapRecognizer release];

If in the view controller, add this in the viewDidLoad (or other proper place):

UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[yourCustomView addGestureRecognizer:tapRecognizer];
[tapRecognizer release];

handler is the same:

- (void)handleTap:(UITapGestureRecognizer*)recognizer
{
    // Do Your thing. 
    if (recognizer.state == UIGestureRecognizerStateEnded)
    {
    }
}

Take a look at the SimpleGestureRecognizers example and you should get a pretty good idea.

---- Updated 10/1/2012----

For those of you who like to use storyboard/nib, this is super simple!

  1. Open your storyboard/nib.

  2. Drag-b-drop the kind of recognizer you want from the Object Library onto the UI element you want.

  3. Right-click on the recognizer object, then connect its selector to an IBAction in the File's Owner (usually an UIViewController.) If you need to, connect the delegate as well.

  4. You're done!




回答2:


I think you need to set the delegate of the gesture recognizer to be whatever view controller you want to handle the taps.

gestureRecognizer.delegate = self;

for example. Then adopt the UIGestureRecognizerDelegate protocol in your header.




回答3:


You can choose the receiver of the UITapGestureRecognizer, it doesn't have to be the same class that instantiated the recognizer (i.e. self). If you create it in your WelcomeViewConroller, you can select any subview to receive the events:

[tapRecognizer addTarget:aSubview action:@selector(myMethod:)];



回答4:


I think you may have the same problem I experienced. When you call [yourCustomView addGestureRecognizer:tapRecognizer]; you need to reference via a UIView * so in your example try:

UIView *mySubView = yourCustomView; 
[mySubView addGestureRecognizer:tapRecognizer];

hope this helps.




回答5:


Please check view.userInteractionEnabled=true;



来源:https://stackoverflow.com/questions/5954934/issue-with-a-uitapgesturerecognizer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!