How can I constrain a subview so that it cannot be

2019-06-09 08:22发布

问题:

How to constrain the position of a subview within its parent view. I have a subview within a UIView. The subview can be dragged via gesture recognizer. How can I constrain the subview so that it cannot be dragged outside of it's parent view's bounds.

回答1:

to constrain a draggable view, you need to check for its position while you move it and then force it to the constrained position if it exceeds the boundaries. So assuming you use touchesMoved :

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

    ...

    CGRect frame = mySubview.frame; 
    if (frame.origin.x < boundaryX) { //frame exceeds the horizontal boundary
        frame.origin.x = boundaryX;
        mySubview.frame = frame;
    }
}

so assuming boundaryX is the origin of the parent view then this way the subview will never exceed that boundary. You need to do the same for origin y and x + width and y + height to do constraints from all sides.

hope this helps.