{
UITouch *touch = [touches anyObject];
if(touch.tapCount == 2)
{
self.view.backgroundColor = [UIColor redColor];
}
}
上面的例子说明在触摸手指离开后,根据 tapCount 点击的次数来设置当前视图的背景色。
不管时一个手指还是多个手指,轻击操作都会使每个触摸对象的
tapCount 加 1,由于上面
的例子不需要知道具体触摸对象的位置或时间等,因此可以直接调用
touches 的 anyObject
方法来获取任意一个触摸对象然后判断其
tapCount 的值即可。
检测 tapCount 可以放在 touchesBegan 也可以 touchesEnded,不过一般后者跟准确,因为
touchesEnded 可以保证所有的手指都已经离开屏幕,这样就不会把轻击动作和按下拖动等
动作混淆。
轻击操作很容易引起歧义,比如当用户点了一次之后,并不知道用户是想单击还是只是
双击的一部分,或者点了两次之后并不知道用户是想双击还是继续点击。为了解决这个问题,
一般可以使用
“延迟调用”函数。
例如:
-(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];
}
}
上面代码表示在第一次轻击之后,没有直接更改视图的背景属性,而是通过
performSelector:withObject:afterDelay:方法设置 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 方法取消指定对象的方法调用,然后
调用双击对应的方法设置背景色为红色。