专注iOS开发其他开发(iOS)

点击事件处理, 以及hitTest:withEvent:实现

2016-04-03  本文已影响6740人  rxdxxxx
touchesBegan…
touchesMoved…
touchedEnded…

一个View是如何判断自己为最佳处理点击事件的View

// recursively calls -pointInside:withEvent:. point is in the receiver's coordinate system
- (nullable UIView *)hitTest:(CGPoint)point withEvent:(nullable UIEvent *)event;


// default returns YES if point is in bounds
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;  

- hitTest: withEvent:方法的底层实现

此底层实现说明了, 一个view的子控件是如何判断是否接收点击事件的.

// 因为所有的视图类都是继承BaseView
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
//    NSLog(@"%@--hitTest",[self class]);
//    return [super hitTest:point withEvent:event];
    
    
    // 1.判断当前控件能否接收事件
    if (self.userInteractionEnabled == NO || self.hidden == YES || self.alpha <= 0.01) return nil;
    
    // 2. 判断点在不在当前控件
    if ([self pointInside:point withEvent:event] == NO) return nil;
    
    // 3.从后往前遍历自己的子控件
    NSInteger count = self.subviews.count;
    
    for (NSInteger i = count - 1; i >= 0; i--) {
        UIView *childView = self.subviews[i];
        
        // 把当前控件上的坐标系转换成子控件上的坐标系
     CGPoint childP = [self convertPoint:point toView:childView];
        
       UIView *fitView = [childView hitTest:childP withEvent:event];
        
        
        if (fitView) { // 寻找到最合适的view
            return fitView;
        }
        
        
    }
    
    // 循环结束,表示没有比自己更合适的view
    return self;
    
}

根据以上的实现, 那么我们就可以重写这个方法, 做一些非常规的效果

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
    
    // 当前控件上的点转换到chatView上
    CGPoint chatP = [self convertPoint:point toView:self.chatView];
    
    // 判断下点在不在chatView上
    if ([self.chatView pointInside:chatP withEvent:event]) {
        return self.chatView;
    }else{
        return [super hitTest:point withEvent:event];
    }
    
}

响应者事件/链条

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

现在有两个View, 一个Blue ,另一个是Yellow.

Yellow是Blue的子控件.

此时你点击Yellow,就会触发Yellow的touchesBegan方法

如何你没有重写Yellow的touchesBegan方法或者调用了[super touchesBegan...],

那么它会触发他下一个响应者的touchesBegan方法, 也就是Blue的touchesBegan方法.

如果这个View是Controller的View, 那么这个View的下一个响应者是控制器.

如果控制器也不处理, 那么把这个事件传递给Controller所在Window.

如果Window也不处理, 那么把事件给UIApplication

如果事件到最后都没人处理, 那么这个事件会被UIApplication丢弃.

上一篇下一篇

猜你喜欢

热点阅读