为什么一个子视图不会留在父框架?

我有一个看法,里面有一个UIImage 。 图像不是静态的,我可以移动它,如果我拖动我的手指(使用拖动事件)问题是,有时图片移动到UIView框架之外。 什么是适当的方法来保持它在父框架边界?

–UIViewA

——– UIViewB

————–的UIImage

————–的UIButton

我想保持UIViewB里面的UIImage

 - (IBAction)myButtonSingleTap:(UIButton *)sender { imDragging = YES; [_myButton addTarget:self action:@selector(dragBegan:withEvent:) forControlEvents: UIControlEventTouchDown]; } - (IBAction)myButtonDragInside:(UIButton *)sender { [_myButton addTarget:self action:@selector(draging:withEvent:) forControlEvents: UIControlEventTouchDragInside]; } - (void)dragBegan:(UIControl *)c withEvent:ev { UITouch *touch = [[ev allTouches] anyObject]; startingTouchPoint = [touch locationInView:self.view]; } - (void)draging:(UIControl *)c withEvent:ev { UITouch *touch = [[ev allTouches] anyObject]; currentTouchPoint = [touch locationInView:self.view]; _movingPic.frame = CGRectMake(currentTouchPoint.x, currentTouchPoint.y, 28, 23); } 

您将需要在拖动过程中检查视图的位置。

在某些时候,您将根据用户的拖动方向等来设置图像的框架。

在这期间,你应该有一个逻辑检查,如…

 If new location x value is less than 0 then set new location x = 0. If new location x value plus image width is greater than view width then set new location x = view width - image width. 

等等…

然后使用新的位置作为移动图像的点。

尝试将触摸识别器添加到父视图,而不是整个视图

在设置新帧之前,请确保它包含在移动视图的超视图边界内。

 - (void)draging:(UIControl *)c withEvent:ev { UITouch *touch = [[ev allTouches] anyObject]; currentTouchPoint = [touch locationInView:self.view]; CGRect newFrame = CGRectMake(currentTouchPoint.x, currentTouchPoint.y, 28, 23); newFrame.x = MAX(newFrame.x, 0); newFrame.y = MAX(newFrame.y, 0); newFrame.x = MIN(newFrame.x, _movingPic.superview.bounds.size.width - 28); newFrame.y = MIN(newFrame.y, _movingPic.superview.bounds.size.height - 23); _movingPic.frame = newFrame; }