2011-07-07 34 views
1

我知道如何拖動一個視圖或對象:拖動查看,從你觸摸它的點iPhone

- (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; 

    } 


} 

,但我想開始拖動該視圖或圖像從我感動的地步。例如,如果我拖動(I強調視圖並置於藍色上的光標):

enter image description here

我開始,如果我拖動鼠標20像素到例如右然後我想視圖拖動力矩也拖累20像素,而不是:

enter image description here

也許我不得不改變看法的地步的,我的拳頭觸摸它的中心。我怎麼能這樣做?

換句話說,我希望做一些事情,當你拖動iPad上的應用程序,如:

enter image description here

回答

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; 
    } 
} 
+0

確保做到location.y - startY還有的X側事情 –

+0

是真的。我忘了提到這個例子只是沿x軸拖動一些東西。 –