How can I constrain a subview so that it cannot be dragged outside of it's parent view's bounds. (iOS)

牧云@^-^@ 提交于 2019-12-23 05:19:30

问题


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.



来源:https://stackoverflow.com/questions/13539521/how-can-i-constrain-a-subview-so-that-it-cannot-be-dragged-outside-of-its-paren

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