简体   繁体   English

UIView。 如何快速找到根 SuperView?

[英]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道格

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):如果您的应用只有一个UIWindow (通常为 true),并且该窗口的唯一子视图是您的根控制器的视图(通常也为 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 .或者您可以通过检查view.superview递归地爬出层次结构,直到找到一个其 superview 为nil的视图。

It's an insignificant amount of processor time to go straight up the superview hierarchy.对于 go 来说,处理器时间的数量是微不足道的。 I have this in my UIView category.我的 UIView 类别中有这个。

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

swift3/4:迅速3/4:

func rootSuperView() -> UIView
{
    var view = self
    while let s = view.superview {
        view = s
    }
    return view
}

I like this one.我喜欢这个。

extension UIView {
    func rootView() -> UIView {
        return superview?.rootView() ?? superview ?? self
    }
}

Fast solution (fast as in minimalist):快速解决方案(极简主义中的快速):

extension UIView {
    var rootView: UIView {
        superview?.rootView ?? self
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在超视图中定位UIView? - How do I position UIView in superview? 当我将UIContainerView添加到视图控制器时,其类型为UIView。 我如何到达嵌入视图的viewcontroller? - When I add a UIContainerView to a view controller it's type is UIView. How do I get to the viewcontroller for the embedded view? 如何找到最父级的SuperView? - How do I find the most parent SuperView? 如何仅使用情节提要使 UILabel 的 UIView 超级视图适合 UILabel 的固有高度? - How do I make the UIView superview of a UILabel fit the intrinsic height of the UILabel using the storyboard only? 如何确定哪个UIView超级视图导致子视图具有userInteractionEnabled = NO? - How do I determine which UIView superview is causing the subview to have userInteractionEnabled = NO? iOS-UIView。 使用drawRect进行数据检索有哪些局限性? - iOS - UIView. What are the limitations of using drawRect to do data retrieval? 如何确保UIView缩小到其超级视图的大小? - How do you ensure that a UIView shrinks down to the size of its superview? UIViewController的根UIView的Superview是否为nil? - Superview of UIViewController's root UIView is nil? ios 在 UIView 内涂漆。 如何改变背景颜色? - ios painting inside UIView. How change background color? 如何在iOS中确定UIImageView的超级视图 - How do I determine the superview of UIImageView in iOS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM