使用自定义uitableviewcells

时间:2012-10-23 06:08:29

标签: ios uitableview

我为我的桌子创建了自定义单元格。基本上我的细胞上有UIButton。我正在重复使用那些细胞。

但是我对这些按钮有困难,因为当重复使用单元格时,它的所有元素也会重复使用,但我希望这些按钮对每个单元都是唯一的。

也许有人可以为此功能提出解决方案?

2 个答案:

答案 0 :(得分:0)

如果您的自定义单元格中有属性button,那该怎么办?

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath    static NSString *CellIdentifier = @"My Cell Identifier";
        MyCustomCellClass *cell = (MyCustomCellClass *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[MyCustomCellClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        }
        // Configure the cell

        UIButton *myButtonForThisCell = [MyButtonArray objectAtIndex:indexPath.row];

        cell.button = myButtonForThisCell;
        return cell;
    }               

答案 1 :(得分:0)

使用两种方法

创建一个buttonView UIVIEW文件
-(NSInteger) getGridIndex
{
    return gridIndex;
}

-(void) setGridIndex:(NSInteger)value
{ 
    gridIndex = value;
}

现在使用cellforrowatindexpath方法

        if (cell == nil) {
                cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
                cell.accessoryType = UITableViewCellAccessoryNone;

        ButtonView *buttonView=[[ButtonView alloc] initWithFrame:CGRectMake(110, 110, 160, 26)];
                buttonView.tag=18;
         UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(55, 0, 60, 26)];
[button addTarget:self action:@selector(ButtonAction:) forControlEvents:UIControlEventTouchUpInside];
         [buttonView addSubview:button];
          [cell addSubview:buttonView];
        }
     ButtonView *buttonView=(ButtonView*)[cell viewWithTag:18];
     NSArray *d=[buttonView subviews];
      UIButton *button=[d objectAtIndex:0];
    //here you can change the setting or title of button or whatever u want to do.
      [buttonView setGridIndex:indexPath.row];
    }

现在按钮操作:

-(void)ButtonAction:(UIButton*)sender{
    ButtonView *view = (ButtonView *)[sender superview];
    NSInteger n=[view getGridIndex];
    //here n is the indexpath.row at which the button was tapped..you can write its action accordingly.
}