【发布时间】:2015-08-08 22:48:47
【问题描述】:
我有一个按钮,当用户点击它时,它会以一种方式运行,而当用户双击它时,它会以另一种方式运行。如果用户双击按钮,我不希望发生单击行为。
如果识别到双击,我如何防止调用 touch down 事件?
【问题讨论】:
标签: ios cocoa-touch ios8 uibutton
我有一个按钮,当用户点击它时,它会以一种方式运行,而当用户双击它时,它会以另一种方式运行。如果用户双击按钮,我不希望发生单击行为。
如果识别到双击,我如何防止调用 touch down 事件?
【问题讨论】:
标签: ios cocoa-touch ios8 uibutton
你可以使用 Target-action;对于 UIControlEvents,您可以像这样使用“UIControlEventTouchDown”和“UIControlEventTouchDownRepeat”:
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!");
}
但是会有0.5秒的延迟!
【讨论】:
据我了解,您希望在同一个按钮上具有不同的行为,因此只需应用两种不同的点击手势。以下代码可能会对您有所帮助。
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];
【讨论】: