天天看点

寻找两个视图的最近公共父视图

- (NSArray<UIView *> *)superViews:(UIView *)view {
    if (view == nil) {
        return @[];
    }
    NSMutableArray *resultMutableArray = [[NSMutableArray alloc] init];
    while (view != nil) {
        [resultMutableArray addObject:view];
        view = view.superview;
    }
    return [resultMutableArray copy];
}

- (UIView *)findParentViewWithView1:(UIView *)view1 otherView:(UIView *)view2 {
    NSArray<UIView *> *arr1 = [self superViews:view1];
    NSArray<UIView *> *arr2 = [self superViews:view2];
    NSSet *set = [NSSet setWithArray:arr2];
    for (int i = 0; i < arr1.count; i++) {
        UIView *view = [arr1 objectAtIndex:i];
        if ([set containsObject:view]) {
            return view;
        }
    }
    return nil;
}