滚动表视图后,UITableViewCell自定义单元格的内容将重置为默认值

时间:2013-11-13 10:04:55

标签: ios uitableview

UITableViewCell自定义单元格的内容,例如UILabel文本,UIButton标题在滚动表格视图后重置为默认值(标签,按钮)。我使用单个表格中的自定义单元格数量视图。这些是我用于在单个表视图中生成多个自定义单元格的代码,具有不同的标识符和每个单元格的不同自定义单元名称。

static NSString *CellIdentifier = @"cell";

UITableViewCell *cell = (customCell1 *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) cell = [[customCell1 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
{
    NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"customCell1" owner:self options:nil];
    for (id currentObject in topLevelObjects)
    {
        if ([currentObject isKindOfClass:[UITableViewCell class]])
        {
            cell = (customCell1 *)currentObject;
            break;
        }
    }
}

static NSString *CellIdentifier2 = @"cell2";

UITableViewCell *cell2 = (customCell2 *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];

if (cell2 == nil) cell2 = [[customCell2 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2];
{
    NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"customCell2" owner:self options:nil];
    for (id currentObject in topLevelObjects)
    {
        if ([currentObject isKindOfClass:[UITableViewCell class]])
        {
            cell2 = (customCell2 *)currentObject;
            break;
        }
    }
}
cell.label = @"Test";
[cell2.button setTitle:@"Test Button" forState:UIControlStateNormal];
return cell;
return cell2;

2 个答案:

答案 0 :(得分:0)

当您将cell / cell2设置为从NIB加载的UITableViewCell时,重用标识符将是XIB中设置的任何内容。

无论如何,你粘贴的代码有很多问题。那是你真正使用的吗?将永远不会返回cell2。

答案 1 :(得分:0)

表视图中的单元格是通过使用单元格标识符出列来动态创建的。在上面提到的代码中,将始终返回“返回单元格”; 数据源方法在创建后一次只能返回一个单元格。因此,如果您想根据使用情况返回一个单元格,您必须执行以下操作

  • (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{   //理想情况下,应该像这样创建自定义单元格

if(condition when you wan this cell1)
{
    //create the custom cell1 here  and return it as given below

    static NSString *cellIdentifier = @"MyCustomCell";

    // Similar to UITableViewCell
    MyCustomCell *cell = (MyCustomCell *)[theTableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[MyCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    return cell1;
}
else if(when you want to create this cell2)
{
   // create the custom cell2 here  and return it
    return cell2;
}
// Create the default UI table view cell and return it . if any of the above condition did not satisfied, it will return the default cell.

//在此处创建默认UI表并返回它     返回细胞; }

相关问题