双击选择器多次触发

时间:2012-06-18 16:11:51

标签: iphone objective-c ios ipad uigesturerecognizer

编辑:我在UIView中有这个方法放在多个视图控制器的顶部,这些视图控制器是UIPageViewController的“数据源”

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setBackgroundColor:[UIColor clearColor]];

        UITapGestureRecognizer *tapGR =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
        [tapGR setDelegate:self];
        [tapGR setNumberOfTapsRequired:1];
        [self addGestureRecognizer:tapGR];


        UITapGestureRecognizer *doubleTapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handleDoubleTap:)];
        [doubleTapGR setNumberOfTapsRequired:2];
        [self addGestureRecognizer:doubleTapGR];

        [tapGR requireGestureRecognizerToFail :doubleTapGR];

        [tapGR release];
        [doubleTapGR release];
    }
    return self;
}

-(void)handleTap:(UITapGestureRecognizer *)tapRecognizer{
    if (!(tapRecognizer.state == UIGestureRecognizerStatePossible)) {
        [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:kTapOnCenterNotificationName object:nil]];
    }
}

-(void)handleDoubleTap:(UITapGestureRecognizer *)doubleTapRecognizer{

    CGPoint point = [doubleTapRecognizer locationInView:self];

    LSSharedVariables *sharedVariables = [LSSharedVariables sharedInstance];
    [sharedVariables setDoubleTapPoint:point];

    [[NSNotificationCenter defaultCenter]postNotification:[NSNotification notificationWithName:kLongPressNotificationName object:nil]];

}

即使我指定仅在手势识别器状态等于UIGestureRecognizerStateEnded时才执行操作,日志会多次显示。我只想在这个块中执行一次动作,我该怎么做?

编辑:我发现双击方法的调用次数是UIPageViewController的页面的很多倍。我无法理解的是为什么singleTapGestureRecognizer不一样。

2 个答案:

答案 0 :(得分:1)

- (void) handleDoubleTap : (UIGestureRecognizer*) sender
{
NSLog (@"Double tap is being handled here");
}

- (void) handleSingleTap : (UIGestureRecognizer*) sender
{
NSLog (@"Single tap is being handled here");
}

- (void) loadView
{
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleSingleTap];

[singleTap requireGestureRecognizerToFail : doubleTap];

[doubleTap setDelaysTouchesBegan : YES];
[singleTap setDelaysTouchesBegan : YES];

[doubleTap setNumberOfTapsRequired : 2];
[singleTap setNumberOfTapsRequired : 1];

[self.view addGestureRecognizer : doubleTap];
[self.view addGestureRecognizer : singleTap];

[singleTap release];
[doubleTap release];
}

试试这个

答案 1 :(得分:0)

听起来你可能有多个对象正在侦听触摸,并且当它发生时都会独立调用“handleDoubleTap”。这可以解释为什么当双击事件发生时你会多次看到它。

我首先会搜索您的代码,以验证您没有多次添加它,因为您遇到的行为不是触摸事件的标准行为。