我试图允许一些UIButton
我的一个视图上的实例被触摸并在屏幕上拖动(最终带有动力,但那是稍后的事!)。我以非常简单的形式工作,如下所示,但问题是通过触摸按钮开始拖动它,它会附着到手指上,并且通过抬起手指,会触发“Touch Up Inside”事件,这是我实际点击按钮时要执行的代码。
简而言之:如何区分点击和拖动/释放?我是否需要将点击更改为短点击手势识别器或类似的识别器?代码:
在viewDidLoad中:
[firstButton addTarget: self action: @selector(wasDragged: withEvent:) forControlEvents: UIControlEventTouchDragInside];
我的 wasDragged 方法:
- (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;
button.center = CGPointMake(button.center.x + delta_x, button.center.y + delta_y);
}
}
你可以使用UIPanGestureRecognizer
并告诉它取消视图中的触摸...
- (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__);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)