ios - 检测 UITableViewCell subview 内的触摸

标签 ios objective-c uitableview

我不清楚应该在何处将 UIGestureRecognizer 代码添加到 UITableViewCell 的相应 subview 中。我已经阅读了所有我能找到的相关问题。现在我的单元格和单元格的 subview 是在 cellForRowAtIndexPath 内部生成的。我试图用这个在 cellForRowAtIndexPath 中添加手势:

UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[mySubview addGestureRecognizer:tapGesture];
tapGesture.cancelsTouchesInView = YES;
tapGesture.delegate = self;

然而,这并没有检测到任何东西。为了验证我的 UIGesture 识别器是否正常工作,我在 tableView 本身上使用了上面的代码,它确实按预期注册了触摸。此外,当 tableView 附加了上述手势时,下面的代码也会按预期被调用:

-(BOOL) gestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    NSLog(@"shouldRevceiveTouch");
    return YES;
}

- (BOOL)gestureRecognizer:(UITapGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UITapGestureRecognizer *)otherGestureRecognizer 
{
    NSLog(@"simultaneously");
    return YES;
}

我试图从 tableView 和 cellForRowAtIndexPath 内部删除 GestureRecognizer 我试图将 GestureRecognizer 附加到单元格本身,它的任何 subview ,没有检测到其他触摸。 (以上代码均未触发)

很明显,我添加的 GestureRecognizer 不正确。添加 GestureRecognizer 的地点/时间是否合适?

谢谢。

最佳答案

我做过类似的事情,但它是 UILongPressGestureRecognizer。我认为没有太大区别(因为所有的触摸都是由 UITableView 接收的)。我在 Controller viewDidLoad 方法(不在单元格中)中添加了手势识别器。

- (void) tableViewLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
    CGPoint p = [gestureRecognizer locationInView:self.messageTableView];

    NSIndexPath *indexPath = [self.messageTableView indexPathForRowAtPoint:p];
    if (indexPath == nil)
        NSLog(@"long press on table view but not on a row");
    else {
        UITableViewCell *cell = [self.messageTableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [cell convertPoint:p fromView:self.messageTableView];
    }
}

你可以把长按改成普通的,自己试试

关于ios - 检测 UITableViewCell subview 内的触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24915118/

相关文章:

ios - Swift iOS - 如何将直接从 TableViewCell 的子类中获取的值传递给 TableView 的 didSelectRow?

ios - UITableViewController 以编程方式访问静态单元格问题

objective-c - UIView animateWithDuration : slows down animation frame rate

ios - 对 NSArray 的 JSON 响应以输出到 UITableView

ios - 绘制前如何清除 subview 的内容

ios - 在屏幕上移动 UIImage

ios - 具有图像文本对齐的 UITableViewCell

ios - setup func 无法更改 viewController 中的背景颜色

objective-c - Cocoa中不同ViewController之间的通信

c++ - 如何将 C++ 变量存储为 NSDictionary 中的值?