Note that there are some explanatory texts on larger screens.

plurals
  1. PODragging a view within a view, constraining it within
    text
    copied!<p>I have a pretty simple bit of code for dragging and drawing.</p> <p>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.</p> <p>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)</p> <p>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.</p> <p>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.</p> <pre><code>-(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]; } } </code></pre> <p>How can I keep him from moving past the edges of his superview?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload