如何讓超出父視圖區域的子視圖實現點擊事件

在父視圖重寫hitTest:withEvent:方法,代碼如下:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    //CGRectMake(50, 50, 100, 100)是相對於該視圖而言的

    if([self isLocationInRectWithPoint:point withRect:CGRectMake(50, 50, 100, 100)]){

        for(UIView *subview in self.subviews){

            if([self isLocationInRectWithPoint:point withRect:subview.frame]){

                return subview;

            }

        }

        return self;

    }

    return nil;

}


//判斷點是否在一個區域裏

- (BOOL)isLocationInRectWithPoint:(CGPoint)point withRect:(CGRect)rect {

    if(point.x >= rect.origin.x && point.x <= rect.origin.x+rect.size.width

       && point.y >= rect.origin.y && point.y <= rect.origin.y+rect.size.height){

        return YES;

    }

    return NO;

}


這時如果子視圖在父視圖區域之外也可以相應事件


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章