[英]Identifying the table cell, when tapping on a Tap Recogniser
我的视图中有一个tableview。 使用自定义单元格创建单元格。 我需要在表格视图单元格中显示一个大字符串,因此我已在Scrollview中添加了文本Label。 当用户点击表格视图单元格时,我还需要执行一些代码。 请看下面的代码:
[cell.textLabelLine2 setFrame:CGRectMake(cell.textLabelLine2.frame.origin.x, cell.textLabelLine2.frame.origin.y, 500, cell.textLabelLine2.frame.size.height)];
cell.scrollView.contentSize = CGSizeMake(cell.textLabelLine2.text.length*10 , 10);
cell.scrollView.pagingEnabled = NO;
问题是,当用户触摸滚动视图上方时,不会调用Tableview的select方法。 我针对此问题找到的解决方案是将手势识别器添加到滚动视图。 但是在这种解决方案中,我们无法检查选择了哪个单元格(或哪个手势识别器)。 有人可以帮我找到解决这个问题的方法吗?
您可以通过以下代码了解单元格
if(gestureRecognizer.state == UIGestureRecognizerStateBegan) {
CGPoint p = [gestureRecognizer locationInView:[self tableView]];
NSIndexPath *indexPath = [[self tableView] indexPathForRowAtPoint:p];
if(indexPath != nil) {
UITableViewCell *cell = [[self tableView] cellForRowAtIndexPath:indexPath];
...
}
}
将滚动视图放在滚动视图中通常是一个坏主意。 UITableView也是UIScrollView。 只有当它们在不同的轴上滚动时(即外部滚动视图垂直滚动而内部滚动水平滚动),这才起作用。
对于您的特定情况,您必须自己触发选择。 一旦有了对单元格的引用,就可以向表视图询问其indexPath。 然后,您自己调用didSelectRow的委托方法。
在带有滚动视图的解决方案中,您无法在滚动视图中滚动,因为gestureRecognizer会“获得”触摸。 因此,我根本不会使用scrollview。
使标签大小调整为其内容,例如:
CGSize customTextLabelSize = [cell.customTextLabel.text sizeWithFont:cell.customTextLabel.font constrainedToSize:CGSizeMake(cell.customTextLabel.frame.size.width, 999999)];
cell.customTextLabel.frame = CGRectMake(cell.customTextLabel.frame.origin.x, cell.customTextLabel.frame.origin.y, cell.customTextLabel.frame.size.width, customTextLabelSize.height);
您还需要在heightForRowAtIndexPath中实现它
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGSize cellSize = [bigTextString sizeWithFont:customTextLabel.font constrainedToSize:CGSizeMake(generalCellWidth, 999999)];
return cellSize.height;
}
这样,您可以只使用didSelectRowAtIndex方法。
如果您确实要使用滚动视图,请在cellForRowAtIndexPath:方法的单元格中添加一个按钮。 使按钮与单元格一样大,并添加一个按钮标签,如下所示:
UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeCustom];
cellButton.frame = CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height);
cellButton.tag = indexPath.row;
[cellButton addTarget:self action:@selector(cellButtonAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:cellButton];
然后加:
-(void)cellButtonAction:(UIButton*)sender
{
//do something with sender.tag
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.