iphone - 我如何拖动按钮?

标签 iphone objective-c cocoa-touch uibutton

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

最佳答案

正如 Jamie 指出的那样,平移手势识别器可能是可行的方法。代码如下所示。

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

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

并且, View Controller 将具有以下目标方法来处理手势:

- (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 坐标。它是不正确的:dragggedButton.frame.origin.x += translation.x。可以更改 View 的框架,但不能直接更改框架的组件。

关于iphone - 我如何拖动按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5696027/

相关文章:

iphone - 在字典中存储整数

ios - 如何在应用程序启动时调用在特定 View Controller 中找到的函数?

ios - 当与核心位置管理器对象结合使用时,initWithCoder 实际上在做什么?

iphone - MKMapview 影响 UINavigationBar 和 TabBar 外观

iphone ios 在单独的线程中运行

iphone - iPhone OS 上的多线程是如何工作的?我该如何使用它?

objective-c - 在 Realm 中添加属性,导致项目崩溃

ios - 使用performSegueWithIdentifier从TableViewCell导航到另一个 View

iphone - iPhone 中调用某些 CTFunction 时出现内存泄漏

objective-c - 将 UIDatePicker 从 12 小时制更改为 24 小时制并返回