检查iphone开发中哪个视图位于顶部

时间:2012-06-28 13:20:57

标签: iphone objective-c ios xcode uiview

我有4个视图并使用4个按钮控制这些视图,我有点混淆如何检查哪个视图位于顶部,我已经尝试了isFirstResponder但它不起作用。如果有人知道请帮助我。提前谢谢。

3 个答案:

答案 0 :(得分:7)

要从subViews获取最顶层视图,请从父视图中获取lastObject

UIView * topMost = [[self.view subviews] lastObject];

答案 1 :(得分:1)

在我开始尝试设置将在同一区域中显示的视图时,有一件事情常常帮助我,我曾经为每个视图设置不同的背景颜色,看看哪一个在顶部。我不知道这是否是您要尝试的设置,但您可以做的另一件事是刷新包含视图,这样您只能“只”拥有您想要的当前视图。

答案 2 :(得分:0)

喜欢这个

UIWindow *window = [[UIApplication sharedApplication].keyWindow;
[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