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

前端 未结 3 1692
悲&欢浪女
悲&欢浪女 2021-02-10 17:55

I\'m trying to allow some UIButton instances on one of my views to be touched and dragged around the screen (eventually with momentum, but that\'s for later!). I ha

相关标签:
3条回答
  • 2021-02-10 18:49

    For beginners like me, I tried UIPanGestureRecognizer as suggested above, but it did not work. So, here is my simple solution: First, add event listeners as suggested by Baig:

    // add drag listener
    [button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
    // add tap listener
    [button addTarget:self action:@selector(wasTapped:) forControlEvents:UIControlEventTouchUpInside];
    

    Both drag and tap will both trigger UIControlEventTouchUpInside, so add a flag in wasDragged:withEvent: like this:

    -(IBAction)wasDragged: (id)sender withEvent: (UIEvent *) event {
        was_dragged = YES;
        UIButton *selected = (UIButton *)sender;
        selected.center = [[[event allTouches] anyObject] locationInView:self.view];
    }
    
    - (IBAction)buttonWasTapped:(id)sender {
        if(!was_dragged)
            NSLog(@"button tapped");
        else{
            was_dragged = NO;
            NSLog(@"button dragged");
        }
    }
    

    Voila. Done.

    0 讨论(0)
  • 2021-02-10 18:49

    Use UIControlEventTouchDragInside and UIControlEventTouchUpInside events of UIButton like

    // add drag listener
    [button addTarget:self action:@selector(wasDragged:withEvent:) forControlEvents:UIControlEventTouchDragInside];
    // add tap listener
    [button addTarget:self action:@selector(wasTapped:) forControlEvents:UIControlEventTouchUpInside];
    

    You can use HBDraggableButton control..

    0 讨论(0)
  • 2021-02-10 18:50

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

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        UIPanGestureRecognizer *panRecognizer;
        panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(wasDragged:)];
        // 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];
    
        button.center = CGPointMake(button.center.x + translation.x, button.center.y + translation.y);
        [recognizer setTranslation:CGPointZero inView:button];
    }
    
    - (IBAction)buttonWasTapped:(id)sender {
        NSLog(@"%s - button tapped",__FUNCTION__);
    }
    
    0 讨论(0)
提交回复
热议问题