iphone - 我怎样才能区分 UITableViewCell 的哪一部分被点击了

标签 iphone ios uitableview

我创建了一个带有自定义 UITableViewCellUITableView。我的单元格在左侧包含一个 UIImageView,在右侧包含一个 UITextView

UITableViewController 中,我在 tableview cellForRowAtIndexPath 中设置了图像和文本。

一切正常,但现在我需要实现 didSelectRowAtIndex 并且我需要区分单元格的 UIImageViewUITextView 是否已被单击。

比方说,图片点击代表删除操作和单元格编辑操作的其余部分。

最佳答案

无需将手势识别器添加到每个单独的单元格,您可以将一个手势识别器添加到 TableView 并确定从用户触摸点选择了哪个单元格,然后确定用户触摸的是图像还是单元格。

首先确保您的 Controller 采用 UIGestureRecognizerDelegate 协议(protocol)。

@interface MyTableViewController() <UIGestureRecognizerDelegate>
@end

然后在加载 View 时将 UIGestureRecognizer 添加到 UITableView

    - (void)viewDidLoad
{
    [super viewDidLoad];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    singleTap.delegate = self;
    singleTap.numberOfTapsRequired = 1;
    singleTap.numberOfTouchesRequired = 1;
    [self.tableView addGestureRecognizer:singleTap];
}

此委托(delegate)方法确定是否应执行 handleTap: 方法。如果它可以从用户触摸中找到 indexPath,则返回 YES,否则返回 NO

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    UITableView *tableView = (UITableView *)gestureRecognizer.view;
    CGPoint p = [gestureRecognizer locationInView:gestureRecognizer.view];
    if ([tableView indexPathForRowAtPoint:p]) {
        return YES;
    }
    return NO;
}

一旦我们确定用户是否点击了单元格,就会调用 handleTap: 方法,然后确定用户是否触摸了图像或单元格的任何其他部分。

- (void)handleTap:(UITapGestureRecognizer *)tap
{
    if (UIGestureRecognizerStateEnded == tap.state) {
        UITableView *tableView = (UITableView *)tap.view;
        CGPoint p = [tap locationInView:tap.view];
        NSIndexPath* indexPath = [tableView indexPathForRowAtPoint:p];
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        CGPoint pointInCell = [tap locationInView:cell];
        if (CGRectContainsPoint(cell.imageView.frame, pointInCell)) {
            // user tapped image
        } else {
            // user tapped cell
        }
    }
}

关于iphone - 我怎样才能区分 UITableViewCell 的哪一部分被点击了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070874/

相关文章:

objective-c - 为 UITableView 的每个部分添加单独的标题

ios - 如何在表格 View 单元格的背景中设置图像动画

iphone - 如何使 ScrollView 的内容透明

iOS CoreData - 使用现有索引预填充数据库

ios - 尺寸图像引脚注释

ios - 滚动 UITableView 以关闭 UIView Above

iphone - iOS中如何访问需要认证的URL

iphone - Objective-C : Proper way to init an NSArray that is a @property

ios - 将 TableView Controller 更改为 Collection View Controller

swift - 表格 View : search bar that uses indexPath. 行