[1]事件的基本概念
UIEvent:事件,是由硬件捕捉的一个表示用户操作设备的对象。
分三类:触摸事件、晃动事件、远程控制事件
触摸事件:用户通过触摸设备屏幕操作对象、输入数据。支持多点触摸,包含1个到多个触摸点
UIView支持触摸事件(因为继承于UIResponder),而且支持多点触摸。
需要定义UIView子类,实现触摸相关的方法。
touches..began、
touches..moved、
touches...ended、
touches..canceled
[2]手势:有规律的触摸。
UITouch代表触摸在屏幕上的一根手指。可以获取触摸时间和触摸位置。
如何获取touch对象。touches集合中包含了视图上的所有⼿势
什么是响应者链
响应者链就是多个响应者对象组成的链
事件的基本概念
UIEvent:事件,是由硬件捕捉的一个表示用户操作设备的对象。
分三类:触摸事件、晃动事件、远程控制事件
触摸事件:用户通过触摸设备屏幕操作对象、输入数据。支持多点触摸,包含1个到多个触摸点
UIView支持触摸事件(因为继承于UIResponder),而且支持多点触摸。
需要定义UIView子类,实现触摸相关的方法。
touches..began、
touches..moved、
touches...ended、
touches..canceled
手势:有规律的触摸。
UITouch代表触摸在屏幕上的一根手指。可以获取触摸时间和触摸位置。
如何获取touch对象。touches集合中包含了视图上的所有⼿势
[3]什么是响应者链
响应者链就是多个响应者对象组成的链
UIResponder。响应者类。
iOS中所有能响应事件(触摸、晃动、远程事件)的对象都是响应者。
系统定义了一个抽象的父类UIResponder来表示响应者。其子类都是响应者
硬件检测到触摸操作,会将信息交给UIApplication,开始检测。
UIApplication -> window -> viewController -> view -> 检测所有⼦子视图
最终确认触摸位置,完成响应者链的查询过程
检测到响应者后,实现touchesBegan:withEvent:等方法,即处理事件。
如果响应者没有处理事件,事件会向下传递。如果没有响应者处理,
则丢弃触摸事件。
事件处理的顺序与触摸检测查询相反。
触摸的⼦视图 -> view -> viewController -> window -> UIApplication
响应者链可以被打断。⽆法完成检测查询过程。
视图类的属性 : userInteractionEnabled。关闭后能阻断查询过程。
#import "TestView.h"
#import "RootView.h"
#define KRandomColor arc4random()%256/255.0
@interface TestView()
{
//开始触摸的点
CGPoint _start;
}
@end
@implementation TestView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor redColor];
}
return self;
}
//开始触摸事件的时候,执行touch 里面的预定的执行事件代码(开始触摸的时候,到这看看)
//一次触摸事件发生时,该方法只执行一次
-(void)touchesBegan:(NSSet *)touches
withEvent:(UIEvent *)event
{
//触摸的时候随机颜色(KRandomColor是在延展里定义的随机数)
self.backgroundColor = [UIColor colorWithRed:KRandomColor green:KRandomColor blue:KRandomColor alpha:1];
//第一次触摸时候的坐标
_start = [[touches anyObject] locationInView:self];
NSLog(@"点我改变颜色");
}
//一次触摸事件尚未结束,会一直调用该方法
//没摸完,就一直摸
-(void)touchesMoved:(NSSet *)touches
withEvent:(UIEvent *)event
{
//移动的点
CGPoint nowPoint = [[touches anyObject] locationInView:self];
//移动的点减去开始触摸的点
CGFloat x = nowPoint.x - _start.x;
CGFloat y = nowPoint.y - _start.y;
CGPoint centerPoint = CGPointMake(self.center.x + x, self.center.y + y);
self.center = centerPoint;
//打印移动时候的坐标
NSLog(@"%@",NSStringFromCGPoint(nowPoint));
}
//一次触摸时间结束,执行该方法
//触摸完成
-(void)touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event
{
NSLog(@"结束了");
}
//触摸时间被别的打断,
//有人打扰
-(void)touchesCancelled:(NSSet *)touches
withEvent:(UIEvent *)event
{
}
@end