iOS 點(diǎn)擊事件分發(fā)機(jī)制

本文將簡(jiǎn)單介紹 iOS 的點(diǎn)擊事件( TouchEvents )分發(fā)機(jī)制和一些使用場(chǎng)景。詳解請(qǐng)看參考部分。

從以下兩個(gè)方面介紹:

1. 尋找 hit-TestView 的過(guò)程(事件的傳遞過(guò)程)
2. 響應(yīng)鏈(事件的響應(yīng)過(guò)程)

一些應(yīng)用場(chǎng)景:

  1. 一個(gè)內(nèi)容是圓形的按鈕(指定只允許視圖的 frame 內(nèi)某個(gè)區(qū)域可以響應(yīng)事件)
  2. tabBar 上中間凸起的按鈕(讓超出父視圖邊界的子視圖區(qū)域也能響應(yīng)事件)

開(kāi)始

尋找 hit-TestView 的過(guò)程的總結(jié)


在 iOS 中,當(dāng)產(chǎn)生一個(gè) touch 事件之后(點(diǎn)擊屏幕),通過(guò) hit-Testing 找到觸摸點(diǎn)所在的 View( hit-TestView )。尋找過(guò)程總結(jié)如下(默認(rèn)情況下):

尋找順序如下:

1. 從視圖層級(jí)最底層的 window 開(kāi)始遍歷它的子 View。
2. 默認(rèn)的遍歷順序是按照 UIView 中 Subviews 的逆順序。
3. 找到 hit-TestView 之后,尋找過(guò)程就結(jié)束了。

確定一個(gè) View 是不是 hit-TestView 的過(guò)程如下:

1. 如果 View 的 userInteractionEnabled = NO,enabled = NO( UIControl ),或者 alpha <= 0.01, hidden = YES 等情況的時(shí)候,直接返回 nil(不再往下判斷)。
2. 如果觸摸點(diǎn)不在 view 中,直接返回 nil。
3. 如果觸摸點(diǎn)在 view 中,逆序遍歷它的子 View ,重復(fù)上面的過(guò)程。
4. 如果 view 的 子view 都返回 nil(都不是 hit-TestVeiw ),那么返回自身(自身是 hit-TestView )。

UIView 提供兩個(gè)方法來(lái)來(lái)確定 hit-TestView:

// 返回一個(gè) hit-TestView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; // recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system

// 判斷觸摸點(diǎn)是否在 view 中
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event; // default returns YES if point is in bounds 

hitTest:withEvent: 方法的具體實(shí)現(xiàn)可以寫(xiě)成這樣:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    //1
    if (self.alpha <= 0.01 || !self.userInteractionEnabled || self.hidden) {
        return nil;
    }
    //2
    if (![self pointInside:point withEvent:event]) {
        return nil;
    }
    //3
    NSEnumerator *enumerator = [self.subviews reverseObjectEnumerator];
    for (UIView *subview in enumerator) {
        UIView *hitTestView = [subview hitTest:point withEvent:event];
        if (hitTestView) {
            return hitTestView;
        }
    }
    //4
    return self;
}

看完了理論,再結(jié)合實(shí)際,這樣就好理解了。

以下講解基于這樣的視圖層級(jí)結(jié)構(gòu)

視圖層級(jí)結(jié)構(gòu).png
+-UIWindow
  +-MainView
    +-RedView
    | +-UIButton
    | +-UIButtonLabel
    +-YellowView
      +-UILabel

下面是測(cè)試過(guò)程中的一些日志(請(qǐng)結(jié)合上面的總結(jié)來(lái)分析):
ps:在實(shí)際項(xiàng)目中點(diǎn)擊一次視圖會(huì)打印兩次下面的信息中間插入一次 UIStatusBarWindow 的信息,目前也不知道什么原因,如果有知道的請(qǐng)分享出來(lái),非常感謝!

點(diǎn)擊紅色 View 時(shí):

UIWindow:[hitTest:withEvent:]
----MainView:[hitTest:withEvent:]
--------YellowView:[hitTest:withEvent:]
--------RedView:[hitTest:withEvent:]
------------UIButton:[hitTest:withEvent:]
hit-TestView is RedView !

分析:

1. 先使用了 YellowView 的 [hitTest:withEvent:] 方法可以看出:默認(rèn)的遍歷順序是按照 UIView(MainView) 中 Subviews 的逆順序。
2. 當(dāng)判斷 YellowView 是不是 hit-TestView 的時(shí)候,判斷觸摸點(diǎn)不在 YellowView 上就不會(huì)再遍歷它的子 View(UILabel) 了。
3. 觸摸點(diǎn)在 RedView 上,所以會(huì)繼續(xù)遍歷它的子 View( UIButton ),觸摸點(diǎn)不在 UIButton 上,所以返回 nil ( UIButton 不是 hit-TestView ),所以返回它本身( 是 hit-TestView )。

點(diǎn)擊灰色 button 時(shí):

UIWindow:[hitTest:withEvent:]
----MainView:[hitTest:withEvent:]
--------YellowView:[hitTest:withEvent:]
--------RedView:[hitTest:withEvent:]
------------UIButton:[hitTest:withEvent:]
----------------UIButtonLabel:[hitTest:withEvent:]
hit-TestView is UIButton !

根據(jù)上面的分析,觸摸點(diǎn)在 RedView 上,所以會(huì)繼續(xù)遍歷它的子 View( UIButton ),觸摸點(diǎn)在 UIButton 上,所以返回它本身( 是 hit-TestView )。

點(diǎn)擊黃色 View 時(shí):

UIWindow:[hitTest:withEvent:]
----MainView:[hitTest:withEvent:]
--------YellowView:[hitTest:withEvent:]
------------UILabel:[hitTest:withEvent:]
hit-TestView is YellowView !

分析:

觸摸點(diǎn)在 YellowView 上,遍歷它的子 View( UILabel ),觸摸點(diǎn)不在 UILabel 上,所以返回 nil,所以 YellowView 是 hit-TestView。找到 hit-TestView 后,就不再檢查 RedView 了。

點(diǎn)擊 label 時(shí):

UIWindow:[hitTest:withEvent:]
UIWindow pointInside:1
----MainView:[hitTest:withEvent:]
MainView pointInside:1
--------YellowView:[hitTest:withEvent:]
YellowView pointInside:1
------------UILabel:[hitTest:withEvent:]
hit-TestView is YellowView !

分析:

觸摸點(diǎn)在 YellowView 上,所以遍歷它的子 View( UILabel ),但是 UILabel 的 userInteractionEnabled = NO,所以返回 nil,這個(gè)時(shí)候其實(shí)還沒(méi)有判斷觸摸點(diǎn)是不是在 UILabel上。

響應(yīng)鏈


找到 hit-TestView 之后,事件就交給它來(lái)處理,hit-TestView 就是 firstResponder(第一響應(yīng)者),如果它無(wú)法響應(yīng)事件(不處理事件),則把事件交給它的 nextResponder(下一個(gè)響應(yīng)者),直到有處理事件的響應(yīng)者或者結(jié)束(傳遞到 AppDelegate 為止)。這一系列的響應(yīng)者和事件的傳遞方向就是響應(yīng)鏈(很形象)。在響應(yīng)鏈中,所有響應(yīng)者的基類(lèi)都是 UIResponder,也就是說(shuō)所有可以響應(yīng)事件的類(lèi)都是 UIResponder 的子類(lèi),UIApplication/UIView/UIViewController 都是 UIResponder 的子類(lèi)。

ps: View 處理事件的方式有手勢(shì)或者重寫(xiě) touchesEvent 方法或者利用系統(tǒng)封裝好的組件( UIControls )。

只要知道 nextResponder 是什么,就可以確定響應(yīng)鏈了。

nextResponder 查找過(guò)程如下:

1. UIView 的 nextResponder 是直接管理它的 UIViewController (也就是 VC.view.nextResponder = VC ),如果當(dāng)前 View 不是 ViewController 直接管理的 View,則 nextResponder 是它的 superView( view.nextResponder = view.superView )。
2. UIViewController 的 nextResponder 是它直接管理的 View 的 superView( VC.nextResponder = VC.view.superView )。
3. UIWindow 的 nextResponder 是 UIApplication 。
4. UIApplication 的 nextResponder 是 AppDelegate。

下面是測(cè)試過(guò)程中的一些日志:

點(diǎn)擊紅色 View 時(shí):

------------------The Responder Chain------------------
RedView
|
MainView
|
ViewController
|
UIWindow
|
UIApplication
|
AppDelegate
------------------The Responder Chain------------------

分析:

1. RedView 不是 UIViewController 管理的 View,所以它的 nextResponder 是它的 superView( MainView )。
2. MainView 是 UIViewController 管理的 View,所以它的 nextResponder 是管理它的 ViewController。
3. ViewController 的 nextResponder 是它管理的 MainView 的superView( UIWindow )。
4. UIWindow 的 nextResponder 是 UIApplication。
5. UIApplication 的 nextResponder 是 AppDelegate。

一般來(lái)說(shuō),某個(gè) UIResponder 的子類(lèi)想要自己處理一些事件,就需要重寫(xiě)它的這些方法:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;

響應(yīng)鏈上的某個(gè)對(duì)象處理事件之后可以選擇讓事件傳遞繼續(xù)下去或者終止,如果需要讓事件繼續(xù)傳遞下去則需要在 touchesBegan 方法里面,調(diào)用父類(lèi)對(duì)應(yīng)的方法:

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // Responding to Touch Events
    [super touchesBegan:touches withEvent:event];
}

下面分享一個(gè)實(shí)際開(kāi)發(fā)中的應(yīng)用場(chǎng)景


場(chǎng)景:自定義一個(gè)這樣的 tabBar,中間有個(gè)凸起一丟丟的 item。

自定義 tabBar.png

UI的實(shí)現(xiàn):自定義一個(gè)大小和 tabBar 一樣的 View 覆蓋在 tabBar 上,然后然后中間的 item 超出自定義 View 的邊界,讓自定義的 View 的 clipsToBounds 為 NO,把超出邊界的部分也顯示出來(lái)。

分析:

根據(jù)尋找 hit-TestView 過(guò)程的原理可以知道,如果點(diǎn)擊超出邊界的部分(凸起的那一丟丟)是不能響應(yīng)事件的。

解決過(guò)程:

1. 打印view的層級(jí)

+-UIWindow
  +-UILayoutContainerView
    +-UITransitionView
    | +-UIViewControllerWrapperView
    | +-UILayoutContainerView
    | +-UINavigationTransitionView
    | | +-UIViewControllerWrapperView
    | | +-UIView
    | +-UINavigationBar
    | +-_UINavigationBarBackground
    | | +-_UIBackdropView
    | | | +-_UIBackdropEffectView
    | | | +-UIView
    | | +-UIImageView
    | +-UINavigationItemView
    | | +-UILabel
    | +-_UINavigationBarBackIndicatorView
    +-MSCustomTabBar
      +-_UITabBarBackgroundView
      | +-_UIBackdropView
      | +-_UIBackdropEffectView
      | +-UIView
      +-UITabBarButton
      +-UITabBarButton
      +-UITabBarButton
      +-UITabBarButton
      +-UIImageView
      +-MSTabBarView
        +-UIButton
        | +-UIImageView
        +-MSVerticalCenterButton
        | +-UIImageView
        | +-UIButtonLabel
        +-MSVerticalCenterButton
        | +-UIImageView
        | +-UIButtonLabel
        +-MSVerticalCenterButton
        | +-UIImageView
        | +-UIButtonLabel
        +-MSVerticalCenterButton
          +-UIImageView
          +-UIButtonLabel

分析:(有點(diǎn)長(zhǎng),不過(guò)只要看 MSCustomTabBar 那部分就可以了)

  • MSTabBarView 就是自定義覆蓋在 MSCustomTabBar 上面的 View,它的子 ViewUIButton 就是中間凸起一丟丟的 item。
  • 如果我們點(diǎn)擊了 tabBar 的內(nèi)部,尋找 hit-TestView 的時(shí)候是會(huì)查詢(xún)自定義的 MSTabBarView 的,從而它的子 View 也會(huì)被查詢(xún),所以只要觸摸點(diǎn)在 view 的范圍內(nèi)就可以響應(yīng)事件了,所以沒(méi)有任何問(wèn)題。
  • 如果我們點(diǎn)擊了凸起的那一丟丟部分,尋找 hit-TestView 的時(shí)候,查詢(xún)到 MSCustomTabBar 之后,由于觸摸點(diǎn)不在它的內(nèi)部,所以不會(huì)查詢(xún)它的子 View( MSTabBarView ),所以凸起的那一丟丟是響應(yīng)不了事件的。所以我們需要重寫(xiě) MSCustomTabBar 的 [hitTest:withEvent:] 方法。

分析 view 的層級(jí)主要是為了確定在哪里重寫(xiě) [hitTest:withEvent:] 方法。

2. 重寫(xiě) [hitTest:withEvent:] 方法,讓超出 tabBar 的那部分也能響應(yīng)事件

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    // 先使用默認(rèn)的方法來(lái)尋找 hit-TestView
    UIView *result = [super hitTest:point withEvent:event];
    // 如果 result 不為 nil,說(shuō)明觸摸事件發(fā)生在 tabbar 里面,直接返回就可以了
    if (result) {
        return result;
    }
    // 到這里說(shuō)明觸摸事件不發(fā)生在 tabBar 里面
    // 這里遍歷那些超出的部分就可以了,不過(guò)這么寫(xiě)比較通用。
    for (UIView *subview in self.tabBarView.subviews) {
        // 把這個(gè)坐標(biāo)從tabbar的坐標(biāo)系轉(zhuǎn)為subview的坐標(biāo)系
        CGPoint subPoint = [subview convertPoint:point fromView:self];
        result = [subview hitTest:subPoint withEvent:event];
        // 如果事件發(fā)生在subView里就返回
        if (result) {
            return result;
        }
    }
    return nil;
}

分析:

如果觸摸點(diǎn)在 tabBar 里面的時(shí)候,使用默認(rèn)方法就可以找到 hit-TestView 了,所以先使用 [super hitTest:point withEvent:event] (因?yàn)槲覀兪侵貙?xiě)方法,所以使用 super 就是使用原始的方法)來(lái)尋找,如果找不到,說(shuō)明觸摸點(diǎn)不在 tabBar 里面,這個(gè)時(shí)候就需要我們手動(dòng)的判斷觸摸點(diǎn)在不在超出的那一丟丟里面了。(其實(shí)只要判斷凸起的 View 就可以了,不過(guò)遍歷所有 子View 比較通用,如果有多個(gè)凸起的 view 也可以這么寫(xiě)),先把坐標(biāo)轉(zhuǎn)換為 子View 的坐標(biāo)(這樣才能使用默認(rèn)的 [pointInside:withEvent:] 方法來(lái)判斷觸摸點(diǎn)是否在 view 里面),然后遍歷 子View 調(diào)用默認(rèn)的 [hitTest:withEvent:] 方法,如果觸摸點(diǎn)在 view 的內(nèi)部,就能找到 hit-TestView,如果遍歷完所有 子View 都沒(méi)有找到 hit-TestView 說(shuō)明觸摸點(diǎn)也不在凸起的那一丟丟里面,然后返回 nil 就可以了。

分享一個(gè)demo


非矩形區(qū)域的點(diǎn)擊:比如一個(gè)圓角為寬度一半的Button,只有點(diǎn)擊圓形區(qū)域才會(huì)響應(yīng)事件。

圓形的 button.png

分析:

因?yàn)橛|摸點(diǎn)在 View 內(nèi),想要限制 view 內(nèi)的點(diǎn)擊區(qū)域,所以重寫(xiě) button 的 [pointInside:withEvent:] 這個(gè)方法。如下:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    // 圓形區(qū)域的半徑
    CGFloat maxRadius = CGRectGetWidth(self.frame)/2;
    // 觸摸點(diǎn)相對(duì)圓心的坐標(biāo)
    CGFloat xOffset = point.x - maxRadius;
    CGFloat yOffset = point.y - maxRadius;
    // 觸摸點(diǎn)的半徑
    CGFloat radius = sqrt(xOffset * xOffset + yOffset * yOffset);

    return radius <= maxRadius;
}

demo 比較簡(jiǎn)單,稍微動(dòng)手一下就可以掌握了。

參考:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容