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.