19

I have a random child view in a view hierarchy. What is the best/fastest/cleverest way to get to the root superview?

Cheers,
Doug

dugla
  • 12,774
  • 26
  • 88
  • 136

4 Answers4

26

If your app only has one UIWindow (usually true), and if that window's only subview is your root controller's view (also usually true):

[randomChildView.window.subviews objectAtIndex:0]

Or you could recursively climb out of the hierarchy, by checking view.superview until you find a view whose superview is nil.

Scott Forbes
  • 7,397
  • 1
  • 26
  • 39
  • 2
    You may want to double check that you will ever find that a "superview is nil" I tried that and got stuck in an infinite loop. – finneycanhelp Apr 08 '12 at 19:19
  • The alternate of climbing only takes a few insignificant processor cycles, and you don't need to assume anything. I don't get an infinite loop. – TJez Nov 08 '13 at 13:54
12

It's an insignificant amount of processor time to go straight up the superview hierarchy. I have this in my UIView category.

- (UIView *)rootView {
    UIView *view = self;
    while (view.superview != Nil) {
        view = view.superview;
    }
    return view;
}

swift3/4:

func rootSuperView() -> UIView
{
    var view = self
    while let s = view.superview {
        view = s
    }
    return view
}
Anton Tropashko
  • 5,486
  • 5
  • 41
  • 66
TJez
  • 1,969
  • 2
  • 19
  • 24
  • 1
    Your method always returns `self.window` – DUzun Sep 12 '14 at 22:40
  • No, it will find the highest UIView element in the hierarchy. Of course if you only run it on views that are under self.window it will only return self.window. – TJez Sep 17 '14 at 12:28
1

I like this one.

extension UIView {
    func rootView() -> UIView {
        return superview?.rootView() ?? superview ?? self
    }
}
Terry Torres
  • 131
  • 1
  • 9
1

Fast solution (fast as in minimalist):

extension UIView {
    var rootView: UIView {
        superview?.rootView ?? self
    }
}
cmaltese
  • 41
  • 2