如何让UIGestureRecognizer工作?

时间:2012-12-17 22:50:27

标签: ios uigesturerecognizer

我在代码中打开手势识别器时遇到了麻烦。我添加了一个handleTap回调到tap手势识别器,但print语句永远不会发生。我只是没有运气。有谁看到我在这里做错了什么?

在我的ViewController.h中

@interface ViewController : UIViewController<UITextFieldDelegate, UIGestureRecognizerDelegate> {

}

@end

这就是我在ViewController.m中的内容

        - (void)viewDidLoad
    {
        [super viewDidLoad];


        CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
        View *myview = [[View alloc] initWithFrame:applicationFrame];



        myview.userInteractionEnabled = YES;
        myview.multipleTouchEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(handleTap)];
        tap.numberOfTapsRequired = 1;
        tap.delegate = self;
        [myview addGestureRecognizer:tap];

        self.view = myview;
    }

-(void)handleTap:(UITapGestureRecognizer*)recognizer {
    NSLog(@"dismiss keyboard");
    //[usernameTextField resignFirstResponder];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}

编辑:我添加了一个文本字段,当我点击文本字段时,我看到了tap选择器的print语句。但是如果我点击文本字段,我就不会得到选择器打印语句。

3 个答案:

答案 0 :(得分:1)

我认为问题在于您的选择器。尝试更改

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

并将其替换为

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

使选择器与handleTap的签名匹配。

答案 1 :(得分:1)

初始化时传递错误的选择器。

该行应如下所示:

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

注意handleTap之后的冒号以匹配您要使用的方法。

答案 2 :(得分:0)

显然是继承UIView并用空函数覆盖drawrect导致选择器被调用。