5

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
  • 1
    I just want to `addSubview(mySubView)` as an overlay of all screen and when remove this subview i want my previous view stay same (like table view scrolled position stay same) –  Dec 17 '15 at 07:32

1 Answers1

3

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)
Kamaal ABOOTHALIB
  • 3,527
  • 1
  • 19
  • 25