UIEvent:
事件,是由设备捕获到用户对硬件的操作. 每个事件都是一个UIEvent对象
iOS中的事件有三种:触摸事件,摇晃事件,以及远程控制事件.
触摸事件:是由用户对屏幕通过接触产生的事件.
对于UIView或者UIView的子类,都能够接收到触摸事件,只是没有对触摸事件作出响应.iOS支持多点触摸.
如果一个视图想要对触摸事件作出响应,只需在该类中实现touchesBegan: touchesEnded:touchesMoved:等触摸方法即可.
<pre name="code" class="objc">//当手指触摸屏幕时触发.(刚开始接触)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//touches 存储触摸屏幕的手指对象.
//每一个手指对象都是一个UITouch类型的对象.
NSLog(@"%lu", (unsigned long)[touches count]);
//单击改变自身颜色,双击修改父视图颜色
//(1)获取手指对象
UITouch *touch1 = [touches anyObject];
//(2)获取手指点击的次数
if ([touch1 tapCount] == 1) {
// [self changeSelfColor];
[self performSelector:@selector(changeSelfColor) withObject:nil afterDelay:0.5];
} else if ([touch1 tapCount] == 2) {
//取消之前的操作,取消之前的任务.
[NSObject
cancelPreviousPerformRequestsWithTarget:self selector:@selector(changeSelfColor) object:nil];
[self changeSuperviewColor];
}
}
//当触摸被取消时触发(前提是手指必须触摸屏幕),比如:电话进入时.
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}
//当手指离开屏幕时触发.(触摸结束)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}
//当手指触摸屏幕,并且在视图内移动时触发.(此时手指不离开屏幕)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"%s", __FUNCTION__);
}
//修改自身视图颜色
- (void)changeSelfColor
{
self.backgroundColor = [UIColor randomColor];
}
//修改父视图颜色
- (void)changeSuperviewColor
{
self.superview.backgroundColor = [UIColor randomColor];
}
//改变自身视图位置
- (void)changeSelfLocation
{
//改变位置
self.center = CGPointMake(arc4random() % (270 - 50 + 1) + 50, arc4random() % (518 - 50 + 1) + 50);
}