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

来源:互联网 发布:java string类split 编辑:程序博客网 时间:2024/05/21 09:48

在创建button的时候可以把indexpath的值给button.tag。点击的时候响应sender.tag.



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

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

两种方法都很好。
-(IBAction):(id)sender
{
 
  NSLog(@"MyRow:%d",[self.tableindexPathForCell:((TableViewCell*)[[sender  superview]superview])].row); //这个方便一点点,不用设置tag。
   NSLog(@"MyRow:%d",((TableViewCell*)[[sendersuperview]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];
    [butsetBackgroundImage:[UIImage imageNamed:@"delete.png"]forState:UIControlStateNormal];
    [butsetFrame:CGRectMake(280, 10, 30, 30)];
    [butsetAlpha:0.8];
    [butaddTarget:self action:@selector(del:)forControlEvents:UIControlEventTouchUpInside];
   [cell.contentView addSubview:but];


    //设置Tag为cell对应的indexPath row
    for(id viewin 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
0 0
原创粉丝点击