lukech lukech - 1 year ago 67
Objective-C Question

Touch and drag a UIButton around, but don't trigger it when releasing the finger

I'm trying to allow some

instances on one of my views to be touched and dragged around the screen (eventually with momentum, but that's for later!). I have this working in a very simple form, shown below, but the problem is that by touching the button to begin dragging it, it attaches to the finger, and by lifting the finger off, the "Touch Up Inside" event is triggered, which is the code I want to execute when actually tapping the button.

In a nutshell: how do I differentiate between a tap, and a drag/release? Do I need to change the tap to a short-tap gesture recognizer, or similar, perhaps? Code:

In viewDidLoad:

[firstButton addTarget: self action: @selector(wasDragged: withEvent:) forControlEvents: UIControlEventTouchDragInside];

And my wasDragged method:

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
if (button == letter1Button) {
UITouch *touch = [[event touchesForView:button] anyObject];

CGPoint previousLocation = [touch previousLocationInView:button];
CGPoint location = [touch locationInView:button];
CGFloat delta_x = location.x - previousLocation.x;
CGFloat delta_y = location.y - previousLocation.y; = CGPointMake( + delta_x, + delta_y);

Answer Source

You could use a UIPanGestureRecognizer and tell it to cancel touches in view...

- (void)viewDidLoad
    [super viewDidLoad];

    UIPanGestureRecognizer *panRecognizer;
    panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
    // cancel touches so that touchUpInside touches are ignored
    panRecognizer.cancelsTouchesInView = YES;
    [[self draggableButton] addGestureRecognizer:panRecognizer];


- (void)wasDragged:(UIPanGestureRecognizer *)recognizer {
    UIButton *button = (UIButton *)recognizer.view;
    CGPoint translation = [recognizer translationInView:button]; = CGPointMake( + translation.x, + translation.y);
    [recognizer setTranslation:CGPointZero inView:button];

- (IBAction)buttonWasTapped:(id)sender {
    NSLog(@"%s - button tapped",__FUNCTION__);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download