IOS 可拖拽按钮

有想过利用UIControlEventTouchDragInside来做的,不过因为按钮需要同时响应UIControlEventTouchUpInside事件,两者会同时触发。

最后使用 UIPanGestureRecognizer解决问题。

摘录事件绑定部分代码。

// 创建手势
UIPanGestureRecognizer* gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onDrag:)];
    gesture.minimumNumberOfTouches = 1;
    gesture.maximumNumberOfTouches = 1;

// debugBall 就是一个可拖动的按钮
[debugBall addGestureRecognizer:gesture];
// debugBall 同时处理touch事件即可    
    [debugBall addTarget:self action:@selector(onDebug) forControlEvents:UIControlEventTouchUpInside];

响应部分逻辑

- (void)onDebug {
    YLog(@"click debug button");
    [self popToRootViewControllerAnimated:YES];
}
- (void) onDrag:(UIPanGestureRecognizer*) sender {
    CGPoint p = [sender locationInView:sender.view.superview];
    
    if(sender.state == UIGestureRecognizerStateEnded || sender.state == UIGestureRecognizerStateFailed) {
        double dx = p.x - lastPoint.x;
        double dy = p.y - lastPoint.y;
        YLog(@"dx %f dy %f", dx, dy);
        if( fabs(dx) < 30 && fabs(dy) < 30 ) {
            [self onDebug];
        }
        
        return;
    }
    
    if(!lastPoint.x && !lastPoint.y) {
        lastPoint.x = p.x;
        lastPoint.y = p.y;
    }
    
    double dx = p.x - lastPoint.x;
    double dy = p.y - lastPoint.y;
    
    debugBall.center = CGPointMake(debugBall.center.x + dx, debugBall.center.y + dy);
    lastPoint = p;
}

你可能感兴趣的:(IOS 可拖拽按钮)