给定一个包含2个或以上视图(UIView
)的任意集合,我想要确定这些视图的最近公共父视图。在Swift中,最有效的算法是什么?
基于以下层次结构:
┌─────┐
│ A │
└─────┘
▲
┌────────────┴────────────┐
│ │
┌─────┐ ┌─────┐ ┌─────┐
│ B │ │ C │ │ X │
└─────┘ └─────┘ └─────┘
▲ ▲ ▲
┌──────┴──────┐ ┌──────┴──────┐ │
│ │ │ │ │
┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐
│ D │ │ E │ │ F │ │ G │ │ Y │ │ Z │
└─────┘ └─────┘ └─────┘ └─────┘ └─────┘ └─────┘
- 如果没有提供视图,则返回 nil。
- 如果提供了 1 个视图,则返回
superview
或 nil。 - 如果任何视图没有
superview
(例如"A","X"或"Z"),则返回 nil。 - 如果视图不属于同一层次结构(例如"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
UIView
。虽然同样适用于NSView
。 - David JamesisDescendantOfView:
的方法,可以用于此目的。因此,通过迭代/while循环遍历第一个视图的superView,检查另一个视图是否是其子孙节点。 - LarmeisDescendant
方法subview.isDescendant(of: self.view)
。 - RajeshKumar R