1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| #import <UIKit/UIKit.h>
@interface UIView (CommonAncestors)
+ (NSArray<UIView *> *)allCommonAncestorsForView:(UIView *)view1 andView:(UIView *)view2;
@end
@implementation UIView (CommonAncestors)
+ (NSArray<UIView *> *)allCommonAncestorsForView:(UIView *)view1 andView:(UIView *)view2 { NSMutableSet<UIView *> *ancestors1 = [NSMutableSet set]; UIView *current = view1; while (current) { [ancestors1 addObject:current]; current = current.superview; }
NSMutableArray<UIView *> *commonAncestors = [NSMutableArray array]; current = view2; while (current) { if ([ancestors1 containsObject:current]) { [commonAncestors addObject:current]; } current = current.superview; }
return [commonAncestors copy]; }
@end
- (void)testAllCommonAncestors { UIView *rootView = [[UIView alloc] init]; UIView *commonParent1 = [[UIView alloc] init]; UIView *commonParent2 = [[UIView alloc] init]; UIView *parent1 = [[UIView alloc] init]; UIView *parent2 = [[UIView alloc] init]; UIView *child1 = [[UIView alloc] init]; UIView *child2 = [[UIView alloc] init];
[rootView addSubview:commonParent1]; [commonParent1 addSubview:commonParent2]; [commonParent2 addSubview:parent1]; [commonParent2 addSubview:parent2]; [parent1 addSubview:child1]; [parent2 addSubview:child2];
NSArray<UIView *> *commonAncestors = [UIView allCommonAncestorsForView:child1 andView:child2]; if (commonAncestors.count > 0) { for (UIView *ancestor in commonAncestors) { NSLog(@"共同父视图: %@", ancestor); } } else { NSLog(@"没有找到共同父视图"); } }
|