拖动UIImageView而不必触摸图像?

时间:2014-04-03 19:48:06

标签: ios iphone xcode5

我的应用程序有一个UIView,其中有一个UIImageView。用户需要能够移动该图像,但不一定要触摸图像。

1 个答案:

答案 0 :(得分:1)

只需声明

NSInteger offsetX;
NSInteger offsetY;

在视图控制器中实现以下方法:

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //Get touch coordinates in location view
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];

    //Calculate offset on touches began
    offsetX = touchPoint.x - imageView.frame.origin.x;
    offsetY = touchPoint.y - imageView.frame.origin.y;
}


-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    //Get touch coordinates in location view
    UITouch *touch = [touches anyObject];
    CGPoint touchPoint = [touch locationInView:self.view];

    //Create new frame with origin offset
    CGRect newFrame = CGRectMake(touchPoint.x - offsetX, touchPoint.y - offsetY, imageView.bounds.size.width, imageView.bounds.size.height);

    //Set the new frame
    imageView.frame = newFrame;
}