我有6个uiimageviews,比如img1 - img6。当我触摸并拖动img1时,它会移动。但是当我拖动img1并且当它接近其他uiimageviews时,img1停止移动并且接近它的img开始移动。当我快速拖动图像而不是慢慢拖动图像时会发生这种情况。拖拉也不是那么顺利...... :(
这是我到目前为止所做的......
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [[event allTouches] anyObject];
if (CGRectContainsPoint([self.firstImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.firstImg];
self.firstImg.center = [touch locationInView:nil];
}
else if (CGRectContainsPoint([self.secondImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.secondImg];
self.secondImg.center = [touch locationInView:nil];
}
else if (CGRectContainsPoint([self.thirdImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.thirdImg];
self.thirdImg.center = [touch locationInView:nil];
}
else if (CGRectContainsPoint([self.fourthImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.fourthImg];
self.fourthImg.center = [touch locationInView:nil];
}
else if (CGRectContainsPoint([self.fifthImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.fifthImg];
self.fifthImg.center = [touch locationInView:nil];
}
else if (CGRectContainsPoint([self.sixthImg frame], [touch locationInView:nil]))
{
[self.view bringSubviewToFront:self.sixthImg];
self.sixthImg.center = [touch locationInView:nil];
}
}
答案 0 :(得分:2)
您的实施存在许多问题:
您将nil
作为视图传递给locationInView:
,这意味着如果移动超视图或支持界面旋转,您将获得不正确的坐标。
您正在将图像视图的中心设置为触摸位置。因此,当用户首次触摸视图时,如果触摸未在视图中精确居中,则视图将跳转到触摸位置的中心。这不是用户期望的行为。
您始终以固定顺序检查视图,而不是从前到后检查视图。这就是为什么“当它接近其他uiimageviews时,img1停止移动并且接近它的img开始移动。”如果触摸超过firstImg
,您的代码将始终移动firstImg
,即使用户正在拖动secondImg
,因为您在检查firstImg
之前始终会检查secondImg
。
你在重复自己。如果你必须两次写同样的东西,你应该考虑将它分解为一个单独的函数或方法。如果你必须写三次(或更多)相同的东西,你几乎肯定会把它排除在外。
所有这些问题的最简单答案是停止使用touchesMoved:withEvent:
及相关方法。相反,为每个图片视图添加UIPanGestureRecognizer
:
- (void)makeImageViewDraggable:(UIImageView *)imageView {
imageView.userInteractionEnabled = YES;
UIPanGestureRecognizer *panner = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewPannerDidFire:)];
[imageView addGestureRecognizer:panner];
}
- (void)imageViewPannerDidFire:(UIPanGestureRecognizer *)panner {
UIView *view = panner.view;
[view.superview bringSubviewToFront:view];
CGPoint translation = [panner locationInView:view];
CGPoint center = view.center;
center.x += translation.x;
center.y += translation.y;
view.center = center;
[panner setTranslation:CGPointZero inView:view];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self makeImageViewDraggable:self.firstImg];
[self makeImageViewDraggable:self.secondImg];
[self makeImageViewDraggable:self.thirdImg];
[self makeImageViewDraggable:self.fourthImg];
[self makeImageViewDraggable:self.fifthImg];
[self makeImageViewDraggable:self.sixthImg];
}