博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

IOS触摸事件

Posted on 2012-04-24 13:21  扬名  阅读(848)  评论(0编辑  收藏  举报

  1.当触摸被取消(比如触摸过程中被来电打断),就会调用touchesCancelled:withEvent方法。

  2.检测tapCount可以放在touchesBegan也可以touchesEnded,不过一般后者跟准确,因为touchesEnded可以保证所有的手指都已经离开屏幕,这样就不会把轻击动作和按下拖动等动作混淆。

  3.轻击操作很容易引起歧义,比如当用户点了一次之后,并不知道用户是想单击还是只是双击的一部分,或者点了两次之后并不知道用户是想双击还是继续点击。为了解决这个问题,一般可以使用“延迟调用”函数。

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch =  [touches anyObject];
    if(touch.tapCount == 1)
    {
        [self performSelector:@selector(setBackground:) withObject:[UIColor blueColor] afterDelay:2];
        self.view.backgroundColor = [UIColor redColor];
    }
}

  上面代码表示在第一次轻击之后,没有直接更改视图的背景属性,而是通过performSelectorwithObjectafterDelay:方法设置2秒中后更改。

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch =  [touches anyObject];
    if(touch.tapCount == 2)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setBackground:) object:[UIColor redColor]];
        self.view.backgroundColor = [UIColor redColor];
    }
}

  双击就是两次单击的组合,因此在第一次点击的时候,设置背景色的方法已经启动,在检测到双击的时候先要把先前对应的方法取消掉,可以通过调用NSObject类的cancelPreviousPerformRequestWithTarget:selector:object方法取消指定对象的方法调用,然后调用双击对应的方法设置背景色为红色。

 

参考:iOS Programming – 触摸事件处理(2)