我有一个观点,里面有一个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);
}
答案 0 :(得分: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.
等...
然后使用新位置作为将图像移动到的点。
答案 1 :(得分:0)
尝试将触控识别器添加到父视图而不是整个视图
答案 2 :(得分: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;
}