我创建了一个带有自定义 UITableViewCell
的 UITableView
。我的单元格在左侧包含一个 UIImageView
,在右侧包含一个 UITextView
。
在 UITableViewController
中,我在 tableview cellForRowAtIndexPath
中设置了图像和文本。
一切正常,但现在我需要实现 didSelectRowAtIndex
并且我需要区分单元格的 UIImageView
或 UITextView
是否已被单击。
比方说,图片点击代表删除操作和单元格编辑操作的其余部分。
最佳答案
无需将手势识别器添加到每个单独的单元格,您可以将一个手势识别器添加到 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/