【问题标题】:Long press event on button [duplicate]按钮上的长按事件[重复]
【发布时间】:2013-01-18 06:28:51
【问题描述】:

可能重复:
How to detect tap on Uitableview cell with uiview and uibutton?
UIButton Long Press Event

我正在通过表格自定义单元格加载按钮。如何识别用户是单击按钮还是长按按钮?

【问题讨论】:

  • 你可以使用LongpressGestureRecognizer...

标签: iphone xcode


【解决方案1】:

我只是谷歌它,我从堆栈溢出This得到了最佳答案

- (void)viewDidLoad
{
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.button addGestureRecognizer:longPress];
    [longPress release];

 [super viewDidLoad];


}

和事件:-

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
         NSLog(@"Long Press");
    }
}

【讨论】:

  • 我的问题是自定义单元格中没有 viewDidLoad
  • 仅在 Viewdidload 中添加此方法是不必要的。在您的自定义单元格中,您只需在您的自定义单元格代码中添加上面的代码,当您在 cellForRowAtindex 等中添加按钮时
  • 分享你的代码我会编辑它
  • 嗨 Nitin,我认为这是重复的问题,您应该将其标记为重复而不是给出答案。
  • 它是stackOVerflow Bro的新用户,我还提到了这个答案的链接,我只是在他们的代码中使用了方法:)'
【解决方案2】:

您可以从创建 UILongPressGestureRecognizer 实例并将其附加到按钮开始。

UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
[self.button addGestureRecognizer:longPress];
[longPress release];

然后实现处理手势的方法

- (void)longPress:(UILongPressGestureRecognizer*)gesture {
    if ( gesture.state == UIGestureRecognizerStateEnded ) {
         NSLog(@"Long Press");
    }
}

现在这将是基本方法。您还可以设置压力机的最短持续时间以及可以容忍的错误量。另请注意,如果您在识别手势后调用该方法几次,因此如果您想在结束时执行某些操作,则必须检查其状态并进行处理。

Reference

【讨论】:

    【解决方案3】:
    - (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];
        }
    }
    
    
    [undoButton addTarget:self action:@selector(performUndo:) forControlEvents:UIControlEventTouchUpInside];
    [undoButton setLongTouchAction:@selector(showUndoOptions:)];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2017-05-09
      相关资源
      最近更新 更多