简体   繁体   中英

Detect if a UIView is behind another UIView in parent

I have a parent UIView with several subviews.

The subviews are siblings - the child-views are not sub views of each other. (Each at the same heirarchical level in their superview)

For instance:

UIView *containerView = [[UIView alloc] initWithFrame:frame];
CustomUIView *childView = [[UIView alloc] initWithFrame:anotherFrame];
CustomUIView *yetAnotherChildView = [[UIView alloc] initWithFrame:anotherFrame];

[containerView addSubview:childView];
[containerView addSubview:yetAnotherChildView];

[containerView bringSubviewToFront:childView];

I want yetAnotherChildView to be able to detect it was moved back in the view heirarchy. How can this be done?

Edit :

I understand that the containerView can know what subviews are above what - but I don't wan't (can't) the containerView notify its subviews that their order changed - Imagine adding a subview ontop of a stock view - the stock view has no idea of its subviews and that they would like to receive such a notification.

The subview CustomUIView would need to observe some change in its superview

for instance (this probably is a very bad solution)

CustomUIView

-(id)initWithFrame
{
  [self.superView addObserver:self forKeyPath:@"subViews" options:options context:context];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
 // if keyPath is "subViews" array check if "this" view is ontop and adjust self accordingly
}

Check their indices in view.subviews array. The one with low index will be at top. So the view at 0 index will be at the top of all others.

You can scan through containerView.subviews and find which one is on which position. If you want to do it on every addSubview - subclass your containerView and add your own addSubview which calls parent class implementation and after that emits notification that subviews array changed (or just do checks right there). In notification handler you can scan through subviews and do whatever you want with order.

Try this it will give you all views behind given view

-(NSMutableArray *)getAllViewsBehindView:(UIView *)view{
NSMutableArray *tempArr = [NSMutableArray array];

NSArray *subViews = view.superview.subviews;

for (int i = 0; (i < subViews.count); i++)
{
    UIView *viewT = [subViews objectAtIndex:i];

    if (viewT == view)
    {
        return tempArr;
    }
    else
    {
        if (CGRectIntersectsRect(viewT.frame, view.frame))
        {
            [tempArr addObject:viewT];
        }
    }

}

return tempArr;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM