UIEvent 事件是有设备捕获到用户对硬件的操作, 每一个事件都是一个UIEvent对象, iOS中的事件分三种: 触摸事件, 摇晃事件, 远程控制事件
触摸事件: 是有用户对屏幕通过触摸产生的事件, 对于UIView 或UIView的子类, 都是能够接收到触摸事件的, 只是没有对触摸事件作出响应, iOS支持多点触摸, 若一个视图相对触摸事件作出响应, 只需在该类中实现, touchesBegan:, touchesEnded:, touchesMoved:等触摸方法即可
摇晃事件
远程控制事件
//当手指触摸屏幕时触发(刚开始接触)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"%s", __FUNCTION__);
//随机色
//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
{
NSLog(@"%s", __FUNCTION__);
}
//当手指离开屏幕时触发(接触结束)
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(@"%s", __FUNCTION__);
// [self changeSelfColor];
// [self changeSuperviewColor];
// [self changeSelfLocation];
}
//当手指触摸屏幕, 并且在视图内移动时触发(此时手指不离开屏幕)
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
// [self changeSelfColor];
// [self changeSuperviewColor];
// self.center = CGPointMake(arc4random() % (270 - 50 + 1) + 50, arc4random() % (518 - 50 + 1) + 50 );
}
//修改自身视图颜色
- (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 );
}
//改变自身视图位置