有想过利用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;
}
网友评论