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

问题描述:

我有一个视图,里面有一个UIImage。图像不是静态的,如果我拖动手指(使用拖动事件),我可以将它移动。问题是,有时图片会移出UIView框架。将其保留在父框架边界内的适当方式是什么?为什么子视图不会留在父框架中?

--UIViewA

-------- UIViewB

-------------- UIImage的

------- ------- UIButton的

我想保持的UIImage内UIViewB

- (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); 
} 
+0

您可以发布您使用的代码/事件处理程序来移动图像吗? – 2013-05-09 11:11:04

+1

clipToBounds = YES只会在图像超出视图时停止显示图像。它不会阻止图像首先出现在视图之外。 – Fogmeister 2013-05-09 11:19:33

+0

使用CGRectContainsRect(,)设置框架检查方法 – 2013-05-09 11:36:51

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

在某些时候,你会设置根据用户的拖动方向等图像的帧...

在此,你应该有一个逻辑检查像...

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. 

etc ...

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

+0

我想过做这样的事情,但希望有一个更优雅的方式,这取决于父框架。 – Segev 2013-05-09 11:23:35

+0

嗯......你可能会使用AutoLayout约束来移动视图,但始终确保约束在父视图内。 (哦,我真的认为这是可能的,而且非常优雅)。 – Fogmeister 2013-05-09 11:23:56

+0

我将我的应用程序定位到iOS 5及更高版本,因此autolayout不存在问题。听起来像一个漂亮的解决方案,但。 – Segev 2013-05-09 11:31:21

尝试添加触摸识别器父视图,而不是entir e查看

+0

我没有使用触摸识别器。我使用的是类似' - (IBAction)myButtonDragInside:(UIButton *)sender {_myButton addTarget:self action:@selector(draging:withEvent :) forControlEvents:UIControlEventTouchDragInside]; }'myButton在子视图中 – Segev 2013-05-09 11:09:50

+0

_myButton的框架和父视图是什么? – Mohith 2013-05-09 11:12:17

+0

我用更多的细节编辑我的问题 – Segev 2013-05-09 11:25:23

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

- (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; 
}