1

我想使用拖动在我的应用程序中移动 UIButton。UIButton 是使用代码创建的。我怎样才能做到这一点?

4

3 回答 3

5

您可以通过以下方式实现此目的:

你可以使用touchesMoved手势或使用UIPanGestureRecognizer

1)使用touchesMoved:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [touch locationInView:self];
    placardView.center = location;
   return;
}

2)使用 UIPanGestureRecognizer

将手势识别器添加到按钮上viewDidLoad,如下所示:

UIPanGestureRecognizer *objGesture= [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moveButton:)];
[myButton addGestureRecognizer:objGesture];
[objGesture release];

编写要调用的目标方法

-(void)moveButton:(UIPanGestureRecognizer *)recognizer
{
if (recognizer.state == UIGestureRecognizerStateChanged || 
    recognizer.state == UIGestureRecognizerStateEnded) {

    UIView *draggedButton = recognizer.view;
    CGPoint translation = [recognizer translationInView:self.view];

    CGRect newButtonFrame = draggedButton.frame;
    newButtonFrame.origin.x += translation.x;
    newButtonFrame.origin.y += translation.y;
    draggedButton.frame = newButtonFrame;

    [recognizer setTranslation:CGPointZero inView:self.view];
}
}
于 2013-03-11T09:16:26.330 回答
0
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
     CGPoint pt = [[touches anyObject] locationInView:self];
     button.center = pt;
}
于 2013-03-11T08:50:44.803 回答
0

尝试使用panGestureRecognizer或通过使用touches方法。单击此处获取更多参考。

于 2013-03-11T09:04:12.663 回答