2012-02-03 108 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