Search code examples
iosswiftuiviewguardsuperview

How to get outermost parent UIView container?


How can I get grand gran parent view of my current self UIView, currently I'm using self.superview?.superview?.superview?.superview?.superview?.superview?

It looks kind of weird, instead of using above syntax is their any other way to get main UIView otherwise how can i preventing this optional chaining with guard?


Solution

  • You can use guard with a method that returns optional, (I assume that you are calling this from UIView custom 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)