How to drag a button?

I have a UIButton that I would like the user to be able to drag and drop using TouchDragInside. How to make the button move when the user moves his finger?

+4
source share
3 answers

As Jamie remarked, a sign of turning recognition is probably the way to go. The code will look something like the one below.

The button controller can 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 to control the gesture, the view controller will have the following target method:

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

FIXED as per rohan-patel comment.

In the previously published code, the x and y coordinates of the start of the button frame were set directly. This was incorrect: draggedButton.frame.origin.x += translation.x . The view frame can be changed, but the components of the frame cannot be changed directly.

+13
source

You probably don't want to use TouchDragInside. This is a method of recognizing that a button or other control is activated in a certain way. To move a button, you probably want to use the UIPanGestureRecognizer, and then reposition the buttons in your supervisor when the user finger moves.

+6
source

You need to implement these four methods: touchsBegan: withEvent :, touchesMoved: withEvent :, touchesEnded: withEvent :, and touchesCancelled: withEvent: in the view that contains the button. The property you are talking about cannot be used directly to drag any uiview

0
source

All Articles