我有一个给定的视图层次结构,如下所示:
View F
> View C
> View D
> View A
> View P
> View B
如何隐藏View C?
我想出了以下逻辑。但是,我想知道这样做是否正确?
func givenViews (view1 : UIView , view2: UIView)
{
aViews = [UIView]()
bViews = [UIView]()
var aView = view1
var bView = view2
// first put all superviews into array
while aView.superview != nil
{
aViews.append(aView)
aView = aView.superview
}
while bView.superview != nil
{
bViews.append(bView)
bView = bView.superview
}
// find the first common view which is C and hide it
for a in aViews
{
for b in bViews
{
if a == b
{
a.hidden = true
break
}
}
}
}
答案 0 :(得分:1)
如果我正确理解您的代码,您将试图隐藏第一个共同祖先。
如果是这样,那么您可以像这样使用isDescendant(of:)
:
func givenViews(view1: UIView, view2: UIView) -> UIView? {
if view2.isDescendant(of: view1) { return view1 }
var aView: UIView? = view1
while let testView = aView, !view2.isDescendant(of: testView) {
aView = testView.superview
}
return aView
}