我如何拖动按钮?

时间:2011-04-17 19:53:41

标签: iphone objective-c cocoa-touch uibutton

我有一个UIButton,我希望用户能够使用TouchDragInside进行拖动。当用户移动手指时,如何让按钮移动?

3 个答案:

答案 0 :(得分:13)

正如Jamie所说,平移手势识别器可能就是这样。代码看起来如下所示。

按钮的视图控制器可能会向按钮添加手势识别器(可能在viewDidLoad中),如下所示:

    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。可以更改视图的框架,但不能直接更改框架的组件。

答案 1 :(得分:6)

您可能不想使用TouchDragInside。这是一种识别按钮或其他控件已经以某种方式被激活的方法。要移动按钮,您可能希望使用UIPanGestureRecognizer,然后在用户手指移动时更改其超级视图中的按钮位置。

答案 2 :(得分:0)

你必须在保存按钮的视图中实现这四个方法,touchesBegan:withEvent:,touchesMoved:withEvent:,touchesEnded:withEvent:和touchesCancelled:withEvent:您引用的属性不能直接用于拖动任何uiview

相关问题