UITapGestureRecognizer 不会取消点击 UITableView 元素



我已经实现了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];
}

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

cell.addCashButton.userInteractionEnabled = NO;

我的建议:

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

如果您在自定义单元格中使用UIButton,则可以使用按钮tagcellForRowAtIndexPath中添加按钮操作方法

,而不是UITapGestureRecognizer

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);
}

最新更新