How to get the external container of the parent UIView?

How can I get a grand parental view of my current one self UIView, currently I'm usingself.superview?.superview?.superview?.superview?.superview?.superview?

It looks weird, instead of using the syntax above, it's their every other way to get the main UIViewone, otherwise how can I prevent this extra chain with guard?

+4
source share
1 answer

You can use guardwith a method that returns an optional parameter (I assume you are calling this from a custom UIView class).

private func outerMostParent(view:UIView)-> UIView? {
    guard let parent  = superview?.superview?.superview?.superview?.superview?.superview
           else{
        return nil
    }
    return parent
}

and then you can do

self.outerMostParent(self)?.addSubview(yourSubview)
+2

Source: https://habr.com/ru/post/1620494/


All Articles