How can I constrain a subview so that it cannot be

2019-06-09 08:04发布

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条回答
欢心
2楼-- · 2019-06-09 08:49

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.

查看更多
登录 后发表回答