iOS 事件响应链

2021-03-18  本文已影响0人  磊Se

iOS中三种事件类型

响应者对象(Responder Object)

响应者对象指的是有响应和处理上述3种事件能力的对象。响应者链就是由一系列响应者对象构成一个层次结构。
UIResponder是所有响应对象的基类,在UIResponder类中定义了处理上述各种事件的接口。我们熟悉的UIApplication、UIWindow、UIViewController、UIView都直接或间接继承自UIResponder,所以它们都是可以构成响应者链的响应者对象。

响应链的传递

盗图真香

这张图清晰的解释了响应链的传递过程:

模拟系统的调用过程

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    if (self.userInteractionEnabled
        && !self.hidden
        && [self pointInside:point withEvent:event]) {
        // 使用reverseObjectEnumerator进行倒序遍历
        for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
            // 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
            CGPoint convertedPoint = [subview convertPoint:point fromView:self];
            UIView *responseView = [subview hitTest:convertedPoint withEvent:event];
            if (responseView) {
                return responseView;
            }
        }
        //无子视图返回自身
        return self;
    }
    return nil;
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    //判断点击位置是否在视图范围内
    if (CGRectContainsPoint(self.bounds, point)) {
        return YES;
    }
    return NO;
}

解决实际问题

1、响应超出父视图外区域的事件

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    if (CGRectContainsPoint(self.bounds, point)) {
        return YES;
    }
    for (UIView *subview in [self.subviews reverseObjectEnumerator]) {
        // 将像素point从view中转换到当前视图中,返回在当前视图中的像素值
        CGPoint convertedPoint = [subview convertPoint:point fromView:self];
        BOOL inside = [subview pointInside:convertedPoint withEvent:event];
        if (inside) {
            return YES;
        }
    }
    return NO;
}

2、面试题superView上添加viewA,viewA上添加viewB,viewB上添加viewC,且B、C都不在各自视图内。此时重写viewB的pointInside:方法并返回YES,点击A和点击B分别响应哪个视图的事件。

    [viewSuper addSubview:viewA];
    [viewA addSubview:viewB];
    [viewB addSubview:viewC];

    UITapGestureRecognizer *tapA = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapA:)];
    [viewA addGestureRecognizer:tapA];
    UITapGestureRecognizer *tapB = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapB:)];
    [viewB addGestureRecognizer:tapB];
    UITapGestureRecognizer *tapC = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapC:)];
    [viewC addGestureRecognizer:tapC];
    UITapGestureRecognizer *tapS = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapS:)];
    [viewSuper addGestureRecognizer:tapS];
    - (void)tapA:(UITapGestureRecognizer *)tap {
      NSLog(@"tapA");
    }

    - (void)tapB:(UITapGestureRecognizer *)tap {
      NSLog(@"tapB");
    }

    - (void)tapC:(UITapGestureRecognizer *)tap {
      NSLog(@"tapC");
    }

    - (void)tapS:(UITapGestureRecognizer *)tap {
      NSLog(@"tapSuper");
    }
  
1616056611363.jpg

答:点击A,响应事件B,打印tapB
解:

上一篇 下一篇

猜你喜欢

热点阅读