ios触摸事件

1. 响应者对象(UIResponder)

学习触摸事件首先要了解一个比较重要的概念-响应者对象(UIResponder)。

在iOS中不是任何对象都能处理事件,只有继承了UIResponder的对象才能接受并处理事件,我们称之为“响应者对象”。

那么为什么继承自UIResponder的类就能够接收并处理事件呢?

因为UIResponder中提供了以下4个对象方法来处理触摸事件。

- (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;
- (void)touchesEstimatedPropertiesUpdated:(NSSet<UITouch *> *)touches NS_AVAILABLE_IOS(9_1);

看下官方说明:意思就是responder要重载这四个方法,也可能会接收到其他的触摸,必须手动取消这些触摸保证正确的行为...语言功底太差,凑合看吧

// Generally, all responders which do custom touch handling should override all four of these methods.
// Your responder will receive either touchesEnded:withEvent: or touchesCancelled:withEvent: for each
// touch it is handling (those touches it received in touchesBegan:withEvent:).
// *** You must handle cancelled touches to ensure correct behavior in your application. Failure to
// do so is very likely to lead to incorrect behavior or crashes.

所以UIApplication、UIWindow、UIView都能接收触摸事件

2. 触摸事件

当用户点击屏幕后,UIApplication 先响应事件,然后传递给UIWindow。如果window可以响应。就开始遍历window的subviews。遍历的过程中,如果第一个遍历的view1可以响应,那就遍历这个view1的subviews(依次这样不停地查找,直至查找到合适的响应事件view)。如果view1不可以响应,那就开始对view2进行判断和子视图的遍历。依次类推view3,view4…… 如果最后没有找到合适的响应view,这个消息就会被抛弃。(整个遍历的过程就是树的先序遍历)。过程如下图:

image.png

参考链接:
https://www.jianshu.com/p/2e074db792ba
https://blog.csdn.net/hello_hwc/article/details/49176867
https://blog.csdn.net/mushaofeng1990/article/details/62434349

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS开发中经常会涉及到触摸事件。本想自己总结一下,但是遇到了这篇文章,感觉总结的已经很到位,特此转载。作者:L...
    WQ_UESTC阅读 6,108评论 4 26
  • 本文主要讲解iOS触摸事件的一系列机制,涉及的问题大致包括: 触摸事件由触屏生成后如何传递到当前应用? 应用接收触...
    baihualinxin阅读 1,226评论 0 9
  • 概览iPhone的成功很大一部分得益于它多点触摸的强大功能,乔布斯让人们认识到手机其实是可以不用按键和手写笔直接操...
    纸简书生阅读 1,476评论 0 6
  • 目录一、基本概念1.1、UITouch1.2、UIEvent1.3、UIResponder二、查找第一响应者三、响...
    barry阅读 1,513评论 0 5
  • 事件类型 在iOS系统中,一共有三种形式的事件:触摸事件(Touch Event),运动事件(Motion Eve...
    RivenL阅读 427评论 0 0