1. 程式人生 > >UIView中新增子檢視UISCrollview後UITouch事件不響應

UIView中新增子檢視UISCrollview後UITouch事件不響應

做跑馬燈元件時,需要在UIView檢視中新增子檢視UIScrollview,以便可以進行多個內容的向上滾動顯示,同時也在UIView中添加了UITouch事件,但是UITouch點選卻沒有響應。

怎麼解決呢?

出現問題原因:UIScrollView自身就有手勢響應的事件,從響應鏈原理來看,觸發響應後,手勢事件被UISCrollView攔截了,不會再往下傳遞給UIScrollView的父檢視,即UIView,所以不會響應UIView中的UITouch事件。

解決方案:

建立一個UIScrollView的category,重寫UITouch方法。

如:UIScrollView+UITouch.h、UIScrollView+UITouch.m,並在UIScrollView+UITouch.m檔案中重寫UITouch方法

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [[self nextResponder] touchesBegan:touches withEvent:event];
    [super touchesBegan:touches withEvent:event];
}

- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [[self nextResponder] touchesCancelled:touches withEvent:event];
    [super touchesCancelled:touches withEvent:event];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [[self nextResponder] touchesEnded:touches withEvent:event];
    [super touchesEnded:touches withEvent:event];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//    [[self nextResponder] touchesMoved:touches withEvent:event];
    [super touchesMoved:touches withEvent:event];
}

注意:響應鏈原理,事件從上往下傳遞

找到touch事件處理的當前檢視,然後就由他接收,之後的響應處理(responder)從下往上傳遞(UIScrollView——>UIView——>UIViewController——>UIWindow——>Appdelegate)。