帮助我了解iPhone touchsBegan实现和拖动UIView

时间:2010-11-21 00:13:27

标签: iphone uiimageview drag touchesbegan

我知道之前已经回答过这个问题(iPhone "touchesBegan" and "touchesMoved" message ... do not move to centre of touch),但我对iPhone开发并不熟悉,所以不明白答案。

基本上,我想要做的是有一个UIImageView响应触摸,在屏幕上移动它。来自Apple的样本认为,当它触摸了Began时,将其中心移动到触摸,然后移动视图。

我想要的是使用UIImagePicker时图像平移。所选图像不会对触摸进行捕捉,而是会从触摸中移开。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

首先,您需要获得第一次触摸屏幕的位置。然后,对于每个“触摸移动”,获取新点的增量x和y坐标,并将图像移动该量。

// This is untested code and I can't even be sure if it compiles
// Hopefully it is verbose enough to help you with that you are
// Trying to do. If not I can update once I get back infront of 
// a Mac.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    lastPoint = [touch locationInView:self.view];
    CGPoint delta = currentPoint - lastPoint;

    currentViewLoc = imageView.center;

    imageView.center.x = currentViewLoc.x - delta.x;
    imageView.center.y = currentViewLoc.y - delta.y;

    currentPoint = lastPoint;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject]; 
    currentPoint = [touch locationInView:self.view];
}

无论如何都是这样的。我希望你能理解我想说的话。