Search code examples
iosobjective-ccocoa-touchuiviewcgrect

UIView convertRect: - finding subview position two views deep


In the pictures below, each rectangle is a UIView. View A has a weak reference to view C. View A creates view D and needs to add it as a subview to view C so that view A is covered completely. I therefore need to get the position of view A relative to view C. Adding view D as a subView of view A at {0,0} is not an option for this particular case - it has to be a subview of C.

View hierarchy starting point View hierarchy starting point

View hierarchy goal point View hierarchy goal point

I've tried every combination of convertRect:toView: and convertRect:fromView: I can think of, passing in combinations of the three views as sender and receiver as well as using their subviews, but there are too many combinations and I just can't understand how it works. I would be really grateful if somebody could post the correct syntax firstly so I can get it working and more importantly so I can work through a working example to understand what the function is actually doing.

Many thanks in advance!


Solution

  • convertRect: is the right way to go :

    let viewD = UIView()
    viewD.frame = viewA.viewC.convertRect(viewA.frame, fromView: viewA.superview!)
    viewA.viewC.addSubview(viewD)
    

    In Objective-C:

    UIView *viewD = [[UIView alloc] init];
    viewD.frame = [viewA.viewC convertRect:viewA.frame fromView:viewA.superview];
    [viewA.viewC addSubview:viewD];