触摸并拖动UIButton,但在释放手指时不要触发它 [英] Touch and drag a UIButton around, but don't trigger it when releasing the finger

查看:196
本文介绍了触摸并拖动UIButton,但在释放手指时不要触发它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的一个视图上允许一些 UIButton 实例被触摸并拖动到屏幕上(最终有动量,但这是为了以后!)。我有一个非常简单的工作方式,如下所示,但问题是通过触摸按钮开始拖动它,它附着在手指上,并通过抬起手指,触发Touch Up Inside事件,这是我想在实际点击按钮时执行的代码。

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 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:

在viewDidLoad中:

In viewDidLoad:

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

我的wasDragged方法:

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;

        button.center = CGPointMake(button.center.x + delta_x, button.center.y + delta_y);
    }
}


推荐答案

你可以使用 UIPanGestureRecognizer 并告诉它取消视图中的触摸......

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__);
}

这篇关于触摸并拖动UIButton,但在释放手指时不要触发它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆