是否可以区分长按和按下按钮?

Abh*_*nav 12 iphone cocoa-touch uibutton uiview

我们可以调用不同的行动/代表来回应两个不同的事件

  1. 点击UIButton
  2. 在UIButton上点击并按住

Bra*_*son 16

是的,使用UILongPressGestureRecognizer(在iPhone OS 3.2+上)实现此功能相当容易.长按将由手势识别器处理,短按将通过按钮的正常操作.

例如,我将UIButton子类化,并添加了以下方法来指定长按触摸动作(longPressGestureRecognizer是一个实例变量):

- (void)setLongTouchAction:(SEL)newValue
{
    if (newValue == NULL)
    {
        [self removeGestureRecognizer:longPressGestureRecognizer];
        [longPressGestureRecognizer release];
        longPressGestureRecognizer = nil;
    }
    else
    {
        [longPressGestureRecognizer release];
        longPressGestureRecognizer = nil;

        longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:[[self allTargets] anyObject] action:newValue];
        [self addGestureRecognizer:longPressGestureRecognizer];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我可以执行以下操作来设置将由同一目标处理的短击和长按操作:

[undoButton addTarget:self action:@selector(performUndo:) forControlEvents:UIControlEventTouchUpInside];
[undoButton setLongTouchAction:@selector(showUndoOptions:)];
Run Code Online (Sandbox Code Playgroud)

如您所见,这对于您在许多iPad应用程序的标题栏中看到的撤消按钮很有用.


she*_*ein 8

布拉德拉森的答案看起来很不错,但这是另一个可能会让你更灵活/控制你想要或可能想做的事情.

你是UIButton的子类,你重写了touchesBegan和touchesEnded方法,这样当用户开始触摸时你会调用

[self performSelector:@selector(detecetedLongTap) withObject:nil afterDelay:1.0];
Run Code Online (Sandbox Code Playgroud)

在触摸中,你打电话给:

[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(detecetedLongTap) object:nil];
Run Code Online (Sandbox Code Playgroud)

如果手指过早抬起则取消该事件.

您可以在此博客文章中获取完整的代码:

http://www.isignmeout.com/adding-long-tap-functionality-uibutton/