如何拖动按钮?

| 我有一个UIButton,我希望用户能够使用TouchDragInside进行拖动。我如何使按钮随着用户的手指移动而移动?     
已邀请:

bab

正如Jamie指出的那样,平移手势识别器可能是解决之道。该代码将类似于以下内容。 按钮的视图控制器可能会向按钮添加一个手势识别器(可能在“ 0”中),如下所示:
    UIPanGestureRecognizer *pangr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    [myButton addGestureRecognizer:pangr];
    [pangr release];
并且,视图控制器将具有以下目标方法来处理手势:
- (void)pan:(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];
    }
}
根据rohan-patel的评论更正。 在先前发布的代码中,直接设置了按钮框架原点的x和y坐标。误为:
draggedButton.frame.origin.x += translation.x
。可以更改视图的框架,但是不能直接更改框架的组件。     
您可能不想使用TouchDragInside。那是一种识别按钮或其他控件已经以某种方式被激活的方法。要移动按钮,您可能要使用UIPanGestureRecognizer,然后在用户手指移动时更改其在超级视图中的位置。     
您必须在持有按钮的视图中实现这四个方法,touchesBegan:withEvent :、 touchesMoved:withEvent :、 touchesEnded:withEvent:和touchesCancelled:withEvent:。您引用的属性不能直接用于拖动任何uiview     

要回复问题请先登录注册