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.
source share