UITableView indexPath.row问题

时间:2013-08-29 10:14:36

标签: ios uitableview

我正在使用一个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。 我哪里错了?

6 个答案:

答案 0 :(得分:9)

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

有更好的方法可以解决这个问题。

  1. 转换按钮框,使其相对于tableview
  2. 向tableView询问新帧起源处的indexPath
  3. -(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);
    }
    

答案 1 :(得分:5)

将Button标记设置为cellForRowAtIndexPath方法之前设置方法

-(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);

}

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

btn.superviewcontentView的{​​{1}}。请改用UITableviewCell

答案 4 :(得分:0)

如果您已经知道单元格内的值,那么

-(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
 }


 }

答案 5 :(得分:0)

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

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