【问题标题】:How to handle touch events and gesture events on a UIButton?如何处理 UIButton 上的触摸事件和手势事件?
【发布时间】:2016-11-14 12:30:59
【问题描述】:

在应用程序中,我有几个创建并添加到 UITableView 的动态按钮,每个按钮都有一个触摸事件 (UIControlEventTouchUpInside) 和一个长按手势 (UILongPressGestureRecognizer),我想一次执行任何一个操作。因此,如果当用户触摸时,只会调用按钮操作。如果用户长按,则将调用长按事件。

目前,即使我长按按钮,它也总是调用动作。

我应该如何处理这些事件?有什么好的建议吗?

【问题讨论】:

标签: ios objective-c uibutton uilongpressgesturerecogni


【解决方案1】:

您可以在按钮操作事件中添加以下代码。我已经为表格视图中的多个复选框完成了此代码。借助此代码,您可以获得 tableview 记录的 IndexPath。我希望它对你有用。

- (IBAction)btnPressed:(UIButton *)sender {

CGPoint touchPoint = [sender convertPoint:CGPointZero toView:self.tblView];
NSIndexPath *indexpath = [self.tblView indexPathForRowAtPoint:touchPoint];
 NSLog(@"%ld",(long)indexpath.row);
}

【讨论】:

    【解决方案2】:

    为了不触发两者,您应该使用全局变量或标记标记按钮,因此在UIControlEventTouchUpInside 的目标中您可以过滤操作。

    所以让我们假设你的UILongPressGestureRecognizer 在触发时调用longPress,并且它在你的自定义单元格中初始化。 & UIControlEventTouchUpInside 调用目标btnPressed

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [self.button addGestureRecognizer:longPress];
    [self.button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
    

    选择器调用,在您的自定义单元格内:

    -(void)longPress:(UIButton*)btn
    {
       // Flag the button,
       self.button.tag = 1;
    
       // Do LongPress stuff.  
    
    }
    

    UIControlEventTouchUpInside 的按钮目标

    - (void)btnPressed:(id)sender { 
    
        UIButton *senderButton = sender;
    
        if(senderButton.tag == 1) {
            // Long press has been executed, set back the flag to 0
            senderButton.tag = 0;
        } else {
            // Long press not executed 
            // Do the TouchUpInside stuff.
        }
    }
    

    【讨论】:

      【解决方案3】:

      在 Tableview 的 cellForRowAtIndex 中使用以下代码:

      [cell.btn addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
      

      并且在 cellForRowAtIndex 之外实现这个方法。

      -(void)btnPressed:(UIButton*)btn
      {
         //Do whatever
      } 
      

      【讨论】:

        【解决方案4】:

        长按使用此代码

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

        而长按方式是

        -(void)longPress:(UIButton*)btn
        {
           //Do whatever
        } 
        

        【讨论】:

          猜你喜欢
          • 2015-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-19
          • 2011-10-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多