您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

iOS 觸摸事件攔截:用 hitTest 讓重疊視圖各自響應手勢

編輯:iOS 技巧大全
[摘要]本文深入講解 iOS 中觸摸事件的攔截機制,透過重寫 hitTest 方法,讓三個互相重疊的視圖能夠在重疊區域各自響應對應的手勢,對學習 iOS 開發很有幫助。

案例:三個堆疊的圖形,如何讓重疊部分觸發對應視圖的手勢

uiview 不接收事件的三種情況

不接收用戶交互:userInteractionEnabled = NO;
隱藏:hidden = YES;
透明度極低:alpha 介於 0 ~ 0.01 之間

值得注意的是,透過 storyBoard 或 xib 建立的視圖,initWithFrame 方法並不會被執行,這時需要改用 - (void)awakeFromNib 來做初始化。

建立三種顏色的視圖

- (void)awakeFromNib {
    RedView *view1 = [[RedView alloc] initWithFrame:CGRectMake(20, 210, 280, 40)];
    [self addSubview:view1];
    self.redView = view1;

    BlueView *view2 = [[BlueView alloc] initWithFrame:CGRectMake(60, 130, 200, 200)];
    [self addSubview:view2];
    [view2 setAlpha:0.5];
    self.blueView = view2;

    GreenView *view3 = [[GreenView alloc] initWithFrame:CGRectMake(80, 150, 160, 160)];
    [self addSubview:view3];
    [view3 setAlpha:0.5];
    self.greenView = view3;
}

手勢攔截的兩個關鍵方法

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;

重寫 hitTest 方法可以攔截用戶觸摸視圖的順序。hitTest 由 window 負責觸發呼叫。

若希望用戶一按下螢幕就立即響應,使用 touchesBegin;若希望用戶離開螢幕時才響應,則使用 touchesEnd。一般來說建議採用 touchesBegin,以免使用者誤以為點擊沒有反應。

接著把 hitTest 傳入的座標點轉換成 redView 座標系下的點,使用 convertPoint:toView::

CGPoint redP = [self convertPoint:point toView:self.redView];

再判斷某個點是否落在視圖內部:

if ([self.greenView pointInside:greenP withEvent:event]) {
    return self.greenView;
}

hitTest 攔截事件的完整程式碼

-(UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    // 1. 判斷當前視圖是否能接受用戶響應
    // self.userInteractionEnabled = YES; self.alpha > 0.01; self.hidden = NO;

    // 2. 遍歷所有子視圖,判斷能否對觸摸做出響應
    // 3. 把 event 交給上級視圖或視圖控制器處理
    // 4. return nil; 代表當前視圖及其子視圖都不響應觸摸

    /* 參數說明:
       point:用戶觸摸位置相對於當前視圖座標系的點。
       以下兩個方法連動使用,以遞歸方式判斷真正響應用戶事件的子視圖:
       - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event;
       - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event;
       這兩個方法僅在攔截觸摸事件時使用,會打斷響應者鏈,平常不要随意調用。
       提醒:除非萬不得已,否則不建議自行重寫 hitTest 方法。 */

    CGPoint redP = [self convertPoint:point toView:self.redView];
    CGPoint greenP = [self convertPoint:point toView:self.greenView];

    if ([self.greenView pointInside:greenP withEvent:event]) {
        return self.greenView;
    }
    NSLog(@"%@", NSStringFromCGPoint(redP));
    if ([self.redView pointInside:redP withEvent:event]) {
        return self.redView;
    }
    return [super hitTest:point withEvent:event];
}

完整程式碼可參考:https://github.com/zhangjinling/IOSProgects/tree/master/%E6%89%8B%E5%8A%BF/03.%E8%A7%A6%E6%91%B8%E4%BA%8B%E4%BB%B6%E6%8B%A6%E6%88%AA

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved