检测UIButton事件何时完成

3

我正在尝试在UIButton上实现拖放功能,它可以正常工作,但是我无法确定如何在用户松开按钮并完成拖动时进行通知。以下代码适用于拖动,但我需要在用户完成拖动并松开按钮时得到通知。

- (void)viewDidLoad
{
    [gesturesBrowserButton addTarget:self action:@selector(wasDragged:withEvent:) 
     forControlEvents:UIControlEventTouchDragInside];

    [gesturesBrowserButton addTarget:self action:@selector(finishedDragging:withEvent:) 
                    forControlEvents:UIControlEventTouchDragExit];
}

- (void)wasDragged:(UIButton *)button withEvent:(UIEvent *)event
{
    // get the touch
    UITouch *touch = [[event touchesForView:button] anyObject];

    // get delta
    CGPoint previousLocation = [touch previousLocationInView:button];
    CGPoint location = [touch locationInView:button];
    CGFloat delta_x = location.x - previousLocation.x;
    CGFloat delta_y = location.y - previousLocation.y;

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

    NSLog(@"was dragged");
}

- (void)finishedDragging:(UIButton *)button withEvent:(UIEvent *)event
{
    //doesn't get called
    NSLog(@"finished dragging");
}
2个回答

11

我认为替换

UIControlEventTouchDragExit

使用

UIControlEventTouchDragExit|UIControlEventTouchUpInside
这是一个解决你问题的好起点。

如果用户将手指拖入控件,然后又拖出来,UIControlEventTouchDragExit不会触发吗?我猜你不想要这种情况。 - Rob Napier

2
我认为你想要的事件是UIControlEventTouchUpInside。这是“当手指在此控件内部时离开触摸”的意思。尽管到目前为止,可能无法获得它。但是如果 UIControlEventTouchUpInside 对你不起作用,我建议使用UIControlEventAllEvents 来捕获所有事件并记录下它们,这样你就可以看到每个事件都被触发了。注意不会获得 UIControlEventTouchDragExit,因为那意味着拖动已经离开了控件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接