Detect if a UIView is behind another UIView in parent

柔情痞子 提交于 2019-12-24 04:14:04

问题


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
}

回答1:


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.




回答2:


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.




回答3:


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;}


来源:https://stackoverflow.com/questions/21431932/detect-if-a-uiview-is-behind-another-uiview-in-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!