終于搞清楚iOS響應者鏈了
首先要清楚幾個關(guān)鍵字:UIResponder
,First responder
UIResponder
是所有響應對象的基類恶耽,在UIResponder類中定義了處理各種事件的接口。我們熟悉的UIApplication批什、 UIViewController社搅、UIWindow和所有繼承自UIView的UIKit類都繼承自UIResponder,所以它們的實例都是可以構(gòu)成響應者鏈的響應者對象形葬。
First responder
(第一響應者)指的是當前接受觸摸的響應者對象(通常是一個UIView對象),即表示當前該對象正在與用戶交互淌实,它是響應者鏈的開端猖腕。整個響應者鏈和事件分發(fā)的使命都是找出第一響應者。
大概過程:
1.Events 發(fā)生
2.hitTest:withEvent:
和 pointInside:withEvent:
查找第一響應者
3.向上傳遞事件
發(fā)生事件 -- 查找事件源 -- 處理事件 大概這么個邏輯
iOS系統(tǒng)檢測到手指觸摸(Touch)操作時會將其打包成一個UIEvent對象放坏,并放入當前活動Application的事件隊列老玛,單例的UIApplication會從事件隊列
中取出觸摸事件并傳遞給UIWindow來處理,
UIWindow
首先會使用hitTest:withEvent:
方法尋找此次Touch事件初始點所在的View蜡豹。尋找的方法就是,從window開始弄诲,遍歷所有的子控件的hitTest:withEvent:
方法娇唯,直到找到或者全部遍歷完成為止凤巨。
具體可以查看這個函數(shù)的說明
找到First responder
后洛搀,運行循環(huán)runLoop(這里可以忽略留美,就知道有個對象干了一件事情就行了)以消息的形式將事件發(fā)送給第一響應者(調(diào)用touch方法)伸刃,使其有機會首先處理事件。如果第一響應者沒有進行處理(沒實現(xiàn)touch方法)捧颅,系統(tǒng)就將事件傳遞給響應者鏈中的下一個響應者(父節(jié)點,父控件)挚币,看看它是否可以進行處理扣典。直到UIApplication,都沒人處理贮尖,就會被丟棄。官方的說法:事件分發(fā)(Event Delivery)
具體的介紹
- ([UIView]hitTest:([CGPoint]point withEvent:([UIEvent] *)event;
不難看懂就不翻譯了薪前,主要是自己回顧使用关斜,如果有其他人看了,實在看不了英文的蚤吹,找個翻譯軟件也行了
Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains a specified point.
This method traverses the view hierarchy by calling the [pointInside:withEvent:] method of each subview to determine which subview should receive a touch event. If [pointInside:withEvent:]returns YES
, then the subview’s hierarchy is similarly traversed until the frontmost view containing the specified point is found. If a view does not contain the point, its branch of the view hierarchy is ignored. You rarely need to call this method yourself, but you might override it to hide touch events from subviews.
This method ignores view objects that are hidden, that have disabled user interactions, or have an alpha level less than 0.01
. This method does not take the view’s content into account when determining a hit. Thus, a view can still be returned even if the specified point is in a transparent portion of that view’s content.
Points that lie outside the receiver’s bounds are never reported as hits, even if they actually lie within one of the receiver’s subviews. This can occur if the current view’s [clipsToBounds] property is set to NO
and the affected subview extends beyond the view’s bounds.
UIControl繁涂,UITapGesturer
對于UIButton那類,繼承自UIControl的扔罪,還是有一點點的區(qū)別的桶雀。但是查找等方法還是一樣的唬复,都是通過hitTest:withEvent:
全肮,只是找到第一響應者后的事件分發(fā)(Event Delivery)
變了。之前是直接調(diào)用第一響應者的Touch事件的休建,但是現(xiàn)在找的是注冊的target對象,調(diào)用注冊的selector方法测砂。
對于添加手勢的情況也是一樣的百匆,只是最后事件分發(fā)
變了
參考鏈接: