在iOS中,通过编程该如何找到最上层的UIView?
换句话说...现在显示的是哪个视图?
比如,我有一个nib文件,在里面有三个视图重叠在一起。在程序中,如果我知道最上层的视图是什么,那么我可以移除它。那么,如何找到位于nib文件最上层的视图呢?
你可以有很多最顶部的视图,因为一个视图不必占据整个屏幕。
如果您想要一个视图的最顶部子视图,可以调用
[yourView subviews];
并且取最后一个(它们按显示顺序排列,最前的在最后)
[[yourView subviews] objectAtIndex:[[yourView subviews] count]];
编辑:这一点从评论中得到改进。
[[yourView subviews] lastObject];
如果您知道您的显示视图控制器,只需将yourView替换为yourController.view即可。
像这样
UIView *topMost = [[self.view subviews] lastObject];
Or like this
UIWindow *window = [[UIApplication sharedApplication].keyWindow;
UIView *topMost = [window findTopMostViewForPoint:CGPointMake(100, 100)];
函数
@implementation UIView (Extra)
- (UIView *)findTopMostViewForPoint:(CGPoint)point
{
for(int i = self.subviews.count - 1; i >= 0; i--)
{
UIView *subview = [self.subviews objectAtIndex:i];
if(!subview.hidden && CGRectContainsPoint(subview.frame, point))
{
CGPoint pointConverted = [self convertPoint:point toView:subview];
return [subview findTopMostViewForPoint:pointConverted];
}
}
return self;
}
- (BOOL)isTopmostViewInWindow
{
if(self.window == nil)
{
return NO;
}
CGPoint centerPointInSelf = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
CGPoint centerPointOfSelfInWindow = [self convertPoint:centerPointInSelf toView:self.window];
UIView *view = [self.window findTopMostViewForPoint:centerPointOfSelfInWindow];
BOOL isTopMost = view == self || [view isDescendantOfView:self];
return isTopMost;
}
@end
yourView
是什么? - James Raitsev