UI-事件处理

事件的概念
  • UIEvent:事件,是由硬件捕捉的一个表示用户操作设备的对象
  • 分三类:触摸事件、晃动事件、远程控制事件
  • 触摸事件:用户通过触摸设备屏幕操作对象、输入数据。支持多点 触摸,包含1个到多个触摸点
实现触摸
  • UIView持触摸事件(因为继承于UIResponder),而且持多点触摸。
  • 需要定义UIView子类,实现触摸相关的方法。
  • touches..begantouches..movedtouches...ended touches..canceled
使用触摸实现手势
  • 手势:有规律的触摸。
  • UITouch代表触摸在屏幕上的手指。可以获取触摸时间和触摸位置。
  • 如何获取touch对象。touches集合中包含了视图上的所有⼿手势。
响应者链
由多个响应者对象组成的链
什么是响应者
UIResponder。响应者类
IOS中所有能响应事件(触摸、晃动、远程事件)的对象都是响应者。
系统定义了一个抽象的父类UIResponder来表示响应者。其子类都是响应者。

//开始触摸时候会进来这个方法里边看看有什么需要执行的操作
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"触摸开始");
    //确定我们手指触摸的点得位置
    _startPoint = [[touches anyObject]locationInView:self];
}

//取消触摸
-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"取消触摸");
}

//在移动的过程中我们会一直走这个方法直到停止
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"我一直在触摸");
    CGPoint nowPoint = [[touches anyObject]locationInView:self];
    //偏移量
    CGFloat x = nowPoint.x - _startPoint.x;
    CGFloat y = nowPoint.y - _startPoint.y;
    self.center= CGPointMake(self.center.x+x, self.center.y+y);
    self.backgroundColor = [UIColor colorWithRed:KRandom green:KRandom blue:KRandom alpha:1];
}

//停止触摸
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    NSLog(@"停止触摸");
}