Search code examples
iphoneobjective-cipadios

restrict a view inside the superview


I'm trying to move a UIView - "A" (Subview) inside another UIView - "B" (SuperView) using the touches moved method. I'm able to move the UIView outside the superview. I want to restrict the UIView inside the Superview bounds. Is there any way there can be a generic method to test if the subview is inside the visible rect of the superview ???


Solution

  • It sounds like you want to constrain the movement of the subview (viewA) to be always completely contained by the superview (viewB). CGRectContainsRect is the right answer, but it must be applied carefully, since a subview frame is specified in it's superview's coordinate system.

    // inside touches moved, compute the newViewAFrame based on the movement
    // but only assign it if it meets the containment constraint:
    
    if (CGRectContainsRect(viewB.bounds, newViewAFrame)) {
        viewA.frame = newViewAFrame;
    }
    

    Notice that we don't mention viewB.frame in the check. viewB's position in it's parent is not relevant to whether viewB contains viewA.