[英]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.