0

我有一个视图,里面有一个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);
}
4

3 回答 3

1

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

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

在此期间,您应该进行逻辑检查,例如...

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...

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

于 2013-05-09T11:21:46.183 回答
0

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

于 2013-05-09T11:05:31.277 回答
0

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

- (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;
}
于 2013-05-09T11:24:30.753 回答