从您触摸iPhone的点拖动视图

Ton*_*Nam 1 iphone xcode objective-c drag ipad

我知道如何拖动视图或对象:

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

    UITouch *touch = [[event allTouches] anyObject];


    if( [touch view] == ViewMain)
    {
       CGPoint location = [touch locationInView:self.view];
       ViewMain.center = location;

    }


}
Run Code Online (Sandbox Code Playgroud)

但是我想从触摸它的那一点开始拖动那个视图或图像.例如,如果我拖动(我突出显示视图并在光标上放置蓝色):

在此输入图像描述

我开始拖动的那一刻,如果我将鼠标向右拖动20 px然后我希望视图也拖动20 px而不是:

在此输入图像描述

也许我必须将视图的中心更改为我触摸它的点.我怎么能这样做?

换句话说,我想在iPad上拖动应用程序时做一些事情:

在此输入图像描述

Ton*_*Nam 10

float startX = 0;
float startY = 0;
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];

    if( [touch view] == ViewMain)
    {
        CGPoint location = [touch locationInView:self.view];
        startX = location.x - ViewMain.center.x;        
        startY = ViewMain.center.y;
    }
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [[event allTouches] anyObject];
    if( [touch view] == ViewMain)
    {
        CGPoint location = [touch locationInView:self.view];
        location.x =location.x - startX;
        location.y = startY;
        ViewMain.center = location;
    }
}
Run Code Online (Sandbox Code Playgroud)