我有一个问题,我想添加一些手势给一个uibutton移动并旋转它,我使用这个代码
[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];
}
}
所有工作我可以旋转按钮并移动按钮,问题是如果我旋转按钮然后移动它...在这种情况下不起作用,我可以移动按钮但不是我想要的地方...问题是什么?
答案 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];