gpt4 book ai didi

swift - Swift 中常见的父 View

转载 作者:可可西里 更新时间:2023-11-01 02:05:22 25 4
gpt4 key购买 nike

给定任意一组 2 个或更多 View (UIView),我想确定这些 View 的(最接近的)公共(public)父级是什么。在 Swift 中对此最有效的算法是什么?

基于这些层次结构:

                    ┌─────┐                                                  
│ A │
└─────┘

┌────────────┴────────────┐
│ │
┌─────┐ ┌─────┐ ┌─────┐
│ B │ │ C │ │ X │
└─────┘ └─────┘ └─────┘
▲ ▲ ▲
┌──────┴──────┐ ┌──────┴──────┐ │
│ │ │ │ │
┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐
│ D │ │ E │ │ F │ │ G │ │ Y │ │ Z │
└─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘
  • 如果没有提供 View ,则返回 nil。
  • 如果提供了 1 个 View ,则返回 superview 或 nil。
  • 如果任何 View 没有superview(例如“A”、“X”或“Z”),则返回 nil。
  • 如果 View 不属于同一层次结构(例如“A”或“X”层次结构),则返回 nil。

例子:

// no views
[].commonParent() // nil
// 1 view
[D].commonParent() // B
// siblings
[D,E].commonParent() // B
// child/parent
[D,B].commonParent() // A
// cousins
[D,F].commonParent() // A
// > 2 views
[D,E,F].commonParent() // A
// with root view
[D,A].commonParent() // nil
// unrelated hierarchies
[D,Y].commonParent() // nil
// unrelated view
[D,Z].commonParent() // nil

最佳答案

我知道这已经过时了,但我听说过这个面试问题并进行了一些搜索以了解它的设置方式,并找到了这个。对于那些在我之后来到这里的人,我觉得让您知道当前的解决方案效率不高很重要,O(n^2)。你不会通过那个技术面试。我是在 objective-c 中完成的,但对任何使用 Swift 的人来说应该是直截了当的。这个想法是使用内存让你不必搜索“n”个元素“m”次,从而导致 O(n)。狩猎愉快!

- (UIView *)commonParentIn:(UIView *)v1 view:(UIView *)v2 {
// key all parent views of one view
NSMutableSet *parentSet = [[NSMutableSet alloc] init];
while (v2) {
[parentSet addObject:v2];
v2 = [v2 superview];
}

// search for all parent views of other view in set and return first found
while (v1) {
if ([parentSet containsObject:v1]) {
return v1;
}
v1 = [v1 superview];
}

return nil;
}

下面是一些测试代码:

UIView *v1 = [[UIView alloc] init];
UIView *v2 = [[UIView alloc] init];
UIView *v3 = [[UIView alloc] init];
UIView *v4 = [[UIView alloc] init];
UIView *v5 = [[UIView alloc] init];
UIView *v6 = [[UIView alloc] init];
UIView *v7 = [[UIView alloc] init];
UIView *v8 = [[UIView alloc] init];
UIView *v9 = [[UIView alloc] init];
UIView *v10 = [[UIView alloc] init];
UIView *v11 = [[UIView alloc] init];
UIView *singleParent = [[UIView alloc] init];
UIView *onlyChild = [[UIView alloc] init];

[v1 addSubview:v2];
[v1 addSubview:v3];
[v1 addSubview:v4];
[v2 addSubview:v5];
[v2 addSubview:v9];
[v5 addSubview:v6];
[v5 addSubview:v10];
[v10 addSubview:v11];
[v4 addSubview:v7];
[v4 addSubview:v8];
[singleParent addSubview:onlyChild];

UIView *found = [self commonParentIn:v11 view:onlyChild];

它有助于绘制 View 树,这样您就知道它们应该在何时何地共享父 View 。然后,只需更改传入的 View 即可进行测试。

关于swift - Swift 中常见的父 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com