I have a UIView which is my VC's view(self.view) inside which I have another UIView added as subview both looks like a square. I would like to limit the movement of subview inside the superview. Basically the subview should not go outside the superview bounds.
I did implement
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// i check if point of touch is inside my superview i set the center i.e
UITouch *touch = [[UITouch allObjects] firstObject];
if (CGRectContainsPoint(subview.frame, [touch locationInView:self.view])) {
// set the center here... i.e
subview.center = [touch locationInView:self.view];
}
This works and subview is moving but it also moves outside the superview; how can I restrict the movement within the superview only?
I even tried something like .
if (CGRectContainsRect(self.view.bounds, subview.frame)) {
// this condition works but i don't know why my subview sticks to the sides of superview if i try to drag it through the bounds of superview
}
I don't do anything in touchesBegan, touchesCancelled, and nothing relevant in touchesEnd as well.
You need to check the "new frame" of the view you are moving, and compare its edges to the bounds of its superview:
This also uses the offset of the touch, instead of centering the view on the touch (so it doesn't "jump to your finger" when you start dragging).
Edit for clarification: In this image, the Blue view class is
DraggableView
... It cannot be dragged outside of its superView (the Red view).