How to refer to the "top" view?

In iOS, programmatically, how can one find that upper majority UIView ?

In other words .. which view is displayed right now?

Say I have a tip with three views stacked on top of each other. Inside the program, I can remove the top view if I know what it is. How can I find out which view is on top of the nib?

+5
source share
3 answers

You can have many views from above, because the view does not have to display the entire screen.

If you want the top main view to be viewed, you can call

[yourView subviews];

and take tje last (they appear in the order of display, most of the front ones)

[[yourView subviews] objectAtIndex:[[yourView subviews] count]];

edit: ( )

[[yourView subviews] lastObject];

, viewController yourView yourController.view

+9

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
+3

Like this

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

All Articles