原理认识
触摸事件
UIEvent
一个UIEvent事件的定义为:第一根手指触摸屏幕到最后一根手指离开屏幕。它记录了事件发生的类型,时间以及多个UITouch事件。
@property(nonatomic,readonly) UIEventType type NS_AVAILABLE_IOS(3_0); //事件的类型
@property(nonatomic,readonly) UIEventSubtype subtype NS_AVAILABLE_IOS(3_0);
@property(nonatomic,readonly) NSTimeInterval timestamp; //事件的时间
@property(nonatomic, readonly, nullable) NSSet <UITouch *> *allTouches; //事件包含的touch对象
UITouch
一个UITouch表示表示一根手指与屏幕的交互,它在一根手指触摸屏幕时被创建,这手指离开屏幕时被销毁,同时通过各种属性记录这跟手指交互的信息。
@property(nonatomic,readonly) NSTimeInterval timestamp; //时间
@property(nonatomic,readonly) UITouchPhase phase; //状态,例如begin,move,end,cancel
@property(nonatomic,readonly) NSUInteger tapCount; // 短时间内单击的次数
@property(nonatomic,readonly) UITouchType type NS_AVAILABLE_IOS(9_0); //类型
@property(nonatomic,readonly) CGFloat majorRadius NS_AVAILABLE_IOS(8_0); //触摸半径
@property(nonatomic,readonly) CGFloat majorRadiusTolerance NS_AVAILABLE_IOS(8_0);
@property(nullable,nonatomic,readonly,strong) UIWindow *window; //触摸所在窗口
@property(nullable,nonatomic,readonly,strong) UIView *view; //触摸所在视图
@property(nullable,nonatomic,readonly,copy) NSArray <UIGestureRecognizer *> *gestureRecognizers NS_AVAILABLE_IOS(3_2); //正在接收该触摸对象的手势识别器
@property(nonatomic,readonly) CGFloat force NS_AVAILABLE_IOS(9_0); //触摸的力度
UIEvent响应
系统的UIResponder类提供了一系列API用于响应触摸事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; //手指触摸到屏幕
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; //手指在屏幕上移动或按压
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; //手指离开屏幕
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event; //触摸被中断,例如触摸时电话呼入
事件的传递
当事件产生后系统就会从顶部视图开始递归向下找到最内部的子view,通过判断点击位置是否在视图frame内,寻找最合适响应事件的对象,如果没有合适对象该事件就会被丢弃。
- 如何寻找第一个可以响应事件的对象?
通过hitTest方法按照视图层级,Application接收到系统传来事件时调用 sendEvent: 发送事件给UIWindow,UIWindow开始传递事件,通过hitTest方法递归遍历返回最合适响应该事件的view。
- hitTest判断是否返回视图有哪些条件?
判断当前视图的子视图中存在或自身适合处理该事件的对象条件有三个