【问题标题】:UITapGestureRecognizer does not cancel tap on UITableView elementsUITapGestureRecognizer 不会取消对 UITableView 元素的点击
【发布时间】:2018-02-14 17:54:03
【问题描述】:

我已经实现了 UITableView,其中每个单元格都包含一些按钮 为了检测用户是否点击表格,我添加了 UITapGestureRecognizer。

我希望单元格中的按钮在用户点击它们时不执行任何操作。 我已经实现了这个选择器:

- (void) backgroundTouched:(UITapGestureRecognizer*)sender {
  UIView *view = sender.view;
  NSLog(@"backgroundTouched %@", view);
}

我看到,当我点击表格上的任何位置时,都会调用此选择器,除非我点击 UITableViewCell 中包含的任何按钮。

我怎样才能避免这种情况?

这是创建 UITapGestureRecognizer 的代码:

pragma mark UISearchControllerDelegate

- (void)didPresentSearchController:(UISearchController *)searchController
{
  NSLog(@"didPresentSearchController");
  self.cancelGesture = [UITapGestureRecognizer new];
  [self.cancelGesture addTarget:self action:@selector(backgroundTouched:)];
  self.cancelGesture.cancelsTouchesInView = YES;
  [self.tableView addGestureRecognizer:self.cancelGesture];
}

【问题讨论】:

  • PL.清除您的疑虑,您想禁用点击表格或按钮吗?
  • 禁用按钮。现在,当我点击按钮时,按钮操作会被调用,而手势选择器不会。我想要相反的方式

标签: ios objective-c uitableview uitapgesturerecognizer


【解决方案1】:

如果您不希望按钮执行任何操作,请禁用按钮的 userInteractionEnabled。

cell.addCashButton.userInteractionEnabled = NO;

【讨论】:

  • 这行得通。尽管在我看来这不是一个非常优雅的解决方案,因为我必须根据 searchController 是否处于活动状态来启用/禁用每个单元格
【解决方案2】:

我的建议:

表格有自己的触摸动作工具,使用它的委托方法didSelectRowAtIndexPath

如果您在自定义单元格中使用UIButton,那么您可以在cellForRowAtIndexPath 中添加按钮操作方法,而不是cellForRowAtIndexPath,按钮的tag 如下所示

cellForRowAtIndexPath方法中

cell.yourButton.tag = indexPath.row
[cell.yourButton addTarget:self  action:@selector(myButtonActionMethod:)  forControlEvents:UIControlEventTouchUpInside]

并声明按钮操作方法

-(void) myButtonActionMethod:(UIButton*)sender
 {
    NSLog(@"you clicked on button %@", sender.tag);
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-17
    • 2021-04-17
    • 2016-12-19
    • 2016-06-08
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 2018-03-16
    相关资源
    最近更新 更多