iOS-触摸事件分发及响应详解

原理认识

触摸事件

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判断是否返回视图有哪些条件?

判断当前视图的子视图中存在或自身适合处理该事件的对象条件有三个࿱

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值