UITableView indexPath.row问题

na1*_*a19 3 uitableview ios

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

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

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

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

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

Mat*_*uch 9

不能依赖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);
}
Run Code Online (Sandbox Code Playgroud)


Nit*_*hel 5

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

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

你的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);

}
Run Code Online (Sandbox Code Playgroud)

  • +1用于使用标记来标识行索引.其他答案似乎使用按钮的超级视图,这通常让我担心视图层次结构可能会改变. (3认同)