简体   繁体   中英

UIButton - prevent call to touch down event when touch repeat is called

I have a button that behaves in one way when user taps on it and another when user double taps on it. In case the user double taps the button, i don't want the single tap behavior to happen.

How can i prevent the call to the touch down event in case double tap was recognized?

You can use Target-action; For UIControlEvents, you can use "UIControlEventTouchDown" and "UIControlEventTouchDownRepeat" like this:

UIButton * button = [UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame = CGRectMake(150, 200, 50, 50);
[button addTarget:self action:@selector(buttonSingleTap:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(buttonMutipleTap:) forControlEvents:UIControlEventTouchDownRepeat];
[self.view addSubview:button];

- (void)buttonSingleTap:(UIButton *)btn{
    [self performSelector:@selector(buttonAction:) withObject:btn afterDelay:0.5];
}

- (void)buttonAction:(UIButton *)sender{
    NSLog(@"single tap");
}

- (void)buttonMutipleTap:(UIButton *)btn{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(buttonAction:) object:btn];
    NSLog(@"mutiple tap!");
}

But there will be 0.5sec to delay!

As I understand you want different behavior on the same button,So simply apply two different tap gesture.The below code may help you.

UIButton *btn1=[[UIButton alloc]init];  //your button

//Two diff method call for two diff behaviour

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(singleTapEvent:)];
UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self  action:@selector(doubleTapEvent:)];

//specify the number of tapping event require to execute code.
singleTap.numberOfTapsRequired = 1;  
doubleTap.numberOfTapsRequired = 2;

[singleTap requireGestureRecognizerToFail:DoubleTap];

//Apply  multiple tap gesture to your  button
[btn1 addGestureRecognizer:singleTap]; 
[btn1 addGestureRecognizer:doubleTap];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM