IOS-处理轻击 事件(单击和双击)

作者: 如风家的秘密 | 来源:发表于2016-08-18 16:11 被阅读1359次

    若直接判断tapCount的次数调用相应的方法,那么为出现奇怪的现象,双击的时候会先调用单击方法,再调用双击方法,那么我们如何解决该问题呢?
    ** 解决方法:
    1.若tapCount==1 延迟调用单击方法(为了判断是否实单双击的处理)**

    if (count == 1) {
            [self performSelector:@selector(sigleTapAction) withObject:nil afterDelay:0.3];
        }```
    **2.若tapCount==2,先取消单击方法的调用,再调用双击方法**
    

    if (count == 2) {
    //取消单击
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sigleTapAction) object:nil];
    [self doubleTapAction];
    }

    *代码如下:*
    

    import "ViewController.h"

    import "MyView.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    • (void)viewDidLoad {
      [super viewDidLoad];

      MyView *view = [[MyView alloc] initWithFrame:CGRectMake(50, 200, 200, 200)];
      view.backgroundColor = [UIColor orangeColor];
      [self.view addSubview:view];

    }

    @end

    import "MyView.h"

    @implementation MyView

    • (instancetype)initWithFrame:(CGRect)frame
      {
      self = [super initWithFrame:frame];
      if (self) {

      }
      return self;
      }

    • (void) sigleTapAction{
      NSLog(@"单击");
      }

    • (void) doubleTapAction {

      NSLog(@"双击");
      }
      //当一个或多个手指触碰到屏幕时

    • (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

      UITouch *touch = [touches anyObject];
      NSInteger count = [touch tapCount];
      //问题:当你双击的时候,会调用单击的方法.

      //重点:双击事件取消单击
      if (count == 1) {
      [self performSelector:@selector(sigleTapAction) withObject:nil afterDelay:0.3];
      }
      if (count == 2) {
      //取消单击
      [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sigleTapAction) object:nil];
      [self doubleTapAction];
      }
      }

    @end```


    运行效果:

    相关文章

      网友评论

        本文标题:IOS-处理轻击 事件(单击和双击)

        本文链接:https://www.haomeiwen.com/subject/wrvvsttx.html