0%

常见算法之Hash

简介

收集 Hash 相关的常见算法

查找两个子视图的共同父视图

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 {
// 获取 view1 的所有父视图
NSMutableSet<UIView *> *ancestors1 = [NSMutableSet set];
UIView *current = view1;
while (current) {
[ancestors1 addObject:current];
current = current.superview;
}

// 获取 view2 的所有父视图,并找到共同的祖先视图
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(@"没有找到共同父视图");
}
}