首页 > 代码库 > [iOS UI进阶 - 3.1] 触摸事件的传递
[iOS UI进阶 - 3.1] 触摸事件的传递
UIApplication会从事件队列中取出最前面的事件,并将事件分发下去以便处理,通常,先发送事件给应用程序的主窗口(keyWindow)
主窗口会在视图层次结构中找到一个最合适的视图来处理触摸事件,这也是整个事件处理过程的第一步
找到合适的视图控件后,就会调用视图控件的touches方法来作具体的事件处理
touchesBegan…
touchesMoved…
userInteractionEnabled = NO
隐藏
hidden = YES
透明
alpha = 0.0 ~ 0.01
提示:UIImageView的userInteractionEnabled默认就是NO,因此UIImageView以及它的子控件默认是不能接收触摸事件的
找到最合适的视图控件后,就会调用控件的touches方法来作具体的事件处理
touchesBegan…
touchesMoved…
touchedEnded…
这些touches方法的默认做法是将事件顺着响应者链条向上传递,将事件交给上一个响应者进行处理
For the app on the left, the event follows this path:
-
The initial view attempts to handle the event or message. If it can’t handle the event, it passes the event to itssuperview, because the initial view is not the top most view in its view controller’s view hierarchy.
-
The superview attempts to handle the event. If the superview can’t handle the event, it passes the event to its superview, because it is still not the top most view in the view hierarchy.
-
The topmost view in the view controller’s view hierarchy attempts to handle the event. If the topmost view can’t handle the event, it passes the event to its view controller.
-
The view controller attempts to handle the event, and if it can’t, passes the event to the window.
-
If the window object can’t handle the event, it passes the event to the singleton app object.
-
If the app object can’t handle the event, it discards the event.
The app on the right follows a slightly different path, but all event delivery paths follow these heuristics:
-
A view passes an event up its view controller’s view hierarchy until it reaches the topmost view.
-
The topmost view passes the event to its view controller.
-
The view controller passes the event to its topmost view’s superview.
Steps 1-3 repeat until the event reaches the root view controller.
-
The root view controller passes the event to the window object.
-
The window passes the event to the app object.
自定义一个view
实现view的touches方法,在方法内部实现具体处理代码
通过touches方法监听view触摸事件,有很明显的几个缺点
必须得自定义view
由于是在view内部的touches方法中监听触摸事件,因此默认情况下,无法让其他外界对象监听view的触摸事件
不容易区分用户的具体手势行为
iOS 3.2之后,苹果推出了手势识别功能(Gesture Recognizer),在触摸事件处理方面,大大简化了开发者的开发难度
[iOS UI进阶 - 3.1] 触摸事件的传递