Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i drag a button?

I have a UIButton that i'd like the user to be able to drag with TouchDragInside. How do i get the button to move as the user moves their finger?

like image 852
Andrew Avatar asked Dec 01 '22 02:12

Andrew


2 Answers

As Jamie noted, a pan gesture recognizer is probably the way to go. The code would look something like what follows.

The button's view controller might add a gesture recognizer to the button (possibly in viewDidLoad) as follows:

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

And, the view controller would have the following target method to handle the gesture:

- (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];
    }
}

CORRECTED as per rohan-patel's comment.

In the previously posted code , the x and y coordinate's of the origin of the button's frame were set directly. It was incorrect as: draggedButton.frame.origin.x += translation.x. A view's frame can be changed, but the frame's components cannot be changed directly.

like image 148
salo.dm Avatar answered Dec 05 '22 10:12

salo.dm


You probably don't want to use TouchDragInside. That is a method of recognizing that a button or other control has been activated in a certain way. To move the button, you probably want to use a UIPanGestureRecognizer and then change the buttons position in its superview as the users finger moves around.

like image 25
Jamie Avatar answered Dec 05 '22 08:12

Jamie