如何得到自定义UITableViewCell中的按钮所在的cell的indexPath.row

在自定义UITableViewCell中创建了一个按钮。

想在点击该按钮时知道该按钮所在的cell在TableView中的行数。就是cell的 indexPath.row

两种方法都很好。
-(IBAction):(id)sender
{
    NSLog(@"MyRow:%d",[self.table indexPathForCell:((TableViewCell*)[[sender   superview]superview])].row); //这个方便一点点,不用设置tag。
    NSLog(@"MyRow:%d",((TableViewCell*)[[sender superview]superview]).tag);
    //这个需要加载cell时设置tag.不过也很方便。
}

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //删除cell.contentView中所有内容,避免以下建立新的重复
    int i = [[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
         [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }


    //添加button
    UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
    [but setBackgroundImage:[UIImage imageNamed:@"delete.png"] forState:UIControlStateNormal];
    [but setFrame:CGRectMake(280, 10, 30, 30)];
    [but setAlpha:0.8];
    [but addTarget:self action:@selector(del:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:but];


    //设置Tag为cell 对应的indexPath row
    for(id view in subviews)
    {
         if([view isKindOfClass:[UIButton class]])
         {
             [view setTag:[indexPath row]];
             //[cell.contentView bringSubviewToFront:view];
         }
    }
}



//Button事件
-(void)del:(id)sender
{
    for(UITableViewCell *cell in visiblecells)
    {
        if(cell.tag == button.tag)
    {
    //button.tag就是对应的[indexPath.row
 
转自:http://blog.sina.com.cn/s/blog_708663ad010153ul.html
原文地址:https://www.cnblogs.com/CityPe/p/6189209.html