如何实现UIButton的双击

项目中需要实现点击一个cell里面的UIImageView实现跳转,双击UIImageView实现商品收藏,很简单的功能,记录一下。


如何实现UIButton的双击_第1张图片
Snip20160411_105.png

思路1:UIImageView上面加手势
缺点:手势点击的时候会先触发cell的点击事件。
1.1首先UIImageView允许与用户交互

如何实现UIButton的双击_第2张图片
Paste_Image.png

1.2 在UIImageView上面添加两个手势,分别为单击手势和双击手势。

UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
    [singleTapGestureRecognizer setNumberOfTapsRequired:1];
 [self.imageViewR addGestureRecognizer:singleTapGestureRecognizer];
    
UITapGestureRecognizer *doubleTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
[doubleTapGestureRecognizer setNumberOfTapsRequired:2];
[self.imageViewR addGestureRecognizer:doubleTapGestureRecognizer];

注意要在手势创建之后设置手势的点击次数setNumberOfTapsRequired来区分。然后再分别实现singleTap:和doubleTap:两个方法。


方法2:完美实现 button 添加Target
2.1 在UIImageView上面加一个透明的和UIImageView大小相同的UIButton, 我们叫它purpleButton,我们将其拖为属性。
2.2 在初始化方法(awakeFromNib 或者 init 之类)中 增加两个target.

[self.purpleButton addTarget:self action:@selector(doubleClick:forEvent:) forControlEvents:UIControlEventTouchDownRepeat];
[self.purpleButton  addTarget:self action:@selector(singleClick:forEvent:) forControlEvents:UIControlEventTouchDown];

注意事件都是touchDown 只不过一个是双击的touchDownRepeat

2.3 通过performSelector实现doubleClick:forEvent: 和 singleClick:forEvent:

单击事件:

-(void)singleClick:(UIButton *)button forEvent:(UIEvent *)event{
   
 [self performSelector:@selector(tabButtonTap:) withObject:button afterDelay:0.2];

}
- (void)tabButtonTap:(UIButton *)sender {
    NSLog(@"单击操作");
}

双击事件:


-(void)doubleClick:(UIButton *)button forEvent:(UIEvent *)event
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tabButtonTap:) object:button];
    
    NSLog(@"双击操作");
    
}

这个方法

 [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tabButtonTap:) object:button];

解释是Cancels perform requests previously registered with performSelector:withObject:afterDelay:
就是把performSelector:withObject:afterDelay:以前注册的请求取消掉,从代码上看就是取消了tabButtonTap:方法。
但是只能在一个运行循环范围内有效。所以通过这样子就把单击的事件取消了,在后面就可以实现双击的操作,而不必担心会先触发单击。

你可能感兴趣的:(如何实现UIButton的双击)