2012-02-03 131 views
1

我有一個問題,我想一些姿態加入到了移動一個UIButton和旋轉它,我用這個代碼拖動和旋轉手勢在iPad上

[self.button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside]; 

    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)]; 
    [self.button addGestureRecognizer:rotationGesture]; 

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event 
    { 
     // get the touch 
     UITouch *touch = [[event touchesForView:self.button] anyObject]; 

     // get delta 
     CGPoint previousLocation = [touch previousLocationInView:self.button]; 
     CGPoint location = [touch locationInView:self.button]; 
     CGFloat delta_x = location.x - previousLocation.x; 
     CGFloat delta_y = location.y - previousLocation.y; 

     // move button 
     self.button.center = CGPointMake(self.button.center.x + delta_x,self.button.center.y + delta_y); 

    } 

    - (void)handleRotate:(UIRotationGestureRecognizer *)recognizer { 
     if(recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) 
     { 
      recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation); 
      [recognizer setRotation:0]; 
     } 
    } 

所有的工作,我可以旋轉按鈕,移動按鈕,問題是如果我旋轉按鈕,然後移動它...在這種情況下不工作,我可以移動按鈕,但不是我想要的地方...問題在哪裏?

回答

1

您正在計算觸摸位置相對於按鈕的差異。當按鈕旋轉時,這不起作用。相反,您應該嘗試相對於按鈕或窗口的超視圖來計算它。

取而代之的是:

CGPoint previousLocation = [touch previousLocationInView:self.button]; 
    CGPoint location = [touch locationInView:self.button]; 

你應該使用這樣的:

CGPoint previousLocation = [touch previousLocationInView:self.button.superview]; 
    CGPoint location = [touch locationInView:self.button.superview]; 
+0

好的,謝謝你... – kikko088 2012-02-05 11:10:48