Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView. How Do I Find the Root SuperView Fast?

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

like image 909
dugla Avatar asked May 28 '11 23:05

dugla


4 Answers

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.

like image 117
Scott Forbes Avatar answered Oct 23 '22 11:10

Scott Forbes


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
}
like image 22
TJez Avatar answered Oct 23 '22 10:10

TJez


I like this one.

extension UIView {
    func rootView() -> UIView {
        return superview?.rootView() ?? superview ?? self
    }
}
like image 25
Terry Torres Avatar answered Oct 23 '22 12:10

Terry Torres


Fast solution (fast as in minimalist):

extension UIView {
    var rootView: UIView {
        superview?.rootView ?? self
    }
}
like image 24
cmaltese Avatar answered Oct 23 '22 12:10

cmaltese