Reputation: 4897
I have a pretty simple bit of code for dragging and drawing.
Three views: The root view is basically the window (with a few interface controls). Within it, I have a "canvas" view. Within the canvas view, I have a third view (a small graphic of a character), which the user is meant to "drag" around within the canvas. The dragging works fine.
The problem is that I can't seem to constrain my "character" within the bounds of the canvas. Ideally, when he runs into the edge of the canvas, he should stop (not spill over into the root view)
The canvas view clips subviews; so he does disappear once he goes over the edge - but I don't want him to disappear, I want him to not be able to go any further.
I also call CGRectIsWithinRect before my animation, which in principle should do the trick. The problem is that the frame of the character isn't updated while the animation is occurring - so as long as he's already moving, he'll keep on moving right of the side of the page.
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UIView * charView = [[canvasView floatingView] retain];
CGPoint pt = [[touches anyObject] locationInView:canvasView];
if (CGRectContainsPoint([canvasView bounds], pt)) {
CGRect charFrame = charView.frame;
CGRect containerFrame = canvasView.frame;
BOOL inTheYard= CGRectContainsRect(containerFrame, charFrame);
if (inTheYard == NO) {
//if we're at the edge, don't go any further
return;
}
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:.2];
CGFloat x = floatingView.center.x + (pt.x - startPoint.x);
CGFloat y = floatingView.center.y + (pt.y - startPoint.y);
CGPoint middle = CGPointMake(x,y);
floatingView.center = middle;
[UIView commitAnimations];
[floatingView release];
}
}
How can I keep him from moving past the edges of his superview?
Upvotes: 0
Views: 573
Reputation: 56625
Instead of checking if the touch event is inside the canvas you can clamp it to be inside. Check the x and y points for the touch event separately and if they are outside the canvas move the character up to the wall on that side of the canvas.
CGFloat w = canvasFrame.frame.size.width;
CGFloat h = canvasFrame.frame.size.height;
if (pt.x < 0) pt.x = 0;
if (pt.x > w) pt.x = w;
if (pt.y < 0) pt.y = 0;
if (pt.y > h) pt.y = h;
This will allow you to keep dragging the character along the wall of the canvas even when the touch event is outside (if you remove the inTheYard check).
Upvotes: 1