UITableView indexPath.row问题

我正在使用一个tableView,它加载一个自定义的UITableViewCell,里面有一个“Tap”按钮。 用户单击按钮时会调用方法。

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {... [btnRowTap addTarget:self action:@selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchDown]; ... return cell; } 

在didButtonTouchUpInside方法中,我试图以下列方式检索所选行的值:

 -(IBAction)didButtonTouchUpInside:(id)sender{ UIButton *btn = (UIButton *) sender; UITableViewCell *cell = (UITableViewCell *)btn.superview; NSIndexPath *indexPath = [matchingCustTable indexPathForCell:cell]; NSLog(@"%d",indexPath.row); } 

问题是,在任何一行点击按钮时,我每次都得到相同的值0。 我哪里错了?

不能依赖UITableViewCell的视图层次结构。 这种方法在iOS7中会失败,因为iOS7会更改单元格的视图层次结构。 您的按钮和UITableViewCell之间会有一个额外的视图。

有更好的方法来处理这个问题。

  1. 转换按钮框架,使其相对于tableview
  2. 向tableView询问新帧原点的indexPath

 -(IBAction)didButtonTouchUpInside:(id)sender{ UIButton *btn = (UIButton *) sender; CGRect buttonFrameInTableView = [btn convertRect:btn.bounds toView:matchingCustTable]; NSIndexPath *indexPath = [matchingCustTable indexPathForRowAtPoint:buttonFrameInTableView.origin]; NSLog(@"%d",indexPath.row); } 

将Button标签设置为cellForRowAtIndexPath方法Befor设置方法如

 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {... btnRowTap.tag=indexPath.row [btnRowTap addTarget:self action:@selector(didButtonTouchUpInside:) forControlEvents:UIControlEventTouchDown]; ... return cell; } 

你的tapped单元格如下: –

 -(IBAction)didButtonTouchUpInside:(id)sender{ { UIButton *button = (UIButton*)sender; NSIndexPath *indPath = [NSIndexPath indexPathForRow:button.tag inSection:0]; //Type cast it to CustomCell UITableViewCell *cell = (UITableViewCell*)[tblView1 cellForRowAtIndexPath:indPath]; NSLog(@"%d",indPath.row); } 

尝试这样,如果您要向单元格内容视图添加按钮,请使用下面的代码。

  UITableViewCell *buttonCell = (UITableViewCell *)sender.superview.superview; UITableView* table1 = (UITableView *)[buttonCell superview]; NSIndexPath* pathOfTheCell = [table1 indexPathForCell:buttonCell]; int rowOfTheCell = [pathOfTheCell row]; int sectionOfTheCell = [pathOfTheCell section]; 

btn.superviewbtn.superviewcontentView 。 请改用btn.superview.superview

如果你已经知道了细胞内部的价值,那么

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ UITableViewCell *currentCell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; if ([currentCell.textLabel.text isEqualToString:@"Your Cell Text value" ]){ //Do theStuff here } } 

这是你的ibAction的代码。你不需要设置任何标签或其他任何东西

  -(IBAction)didButtonTouchUpInside:(id)sender{ NSIndexPath *indexPath = [tbl indexPathForCell:(UITableViewCell *)[[sender superview] superview]]; }