2013-12-17 49 views
0

编辑:更新代码来完成我想要做的事情。在UITableviewCell中管理视图

我有一个表格视图,我想动态地将视图数组加载到行中。

例如,如果我的数组中有两个对象:{UITextField object, UIImage image}我希望第一行显示文本字段,第二行显示图像。我不知道如何刷新/管理内容,所以他们不会相互添加。当我滚动时,随着单元在队列中重用,图像和文本字段会相互叠加。

让我们假设我的数组项目被称为arrayOfItems,并包含我想要显示的文本字段或图像列表。

根据下面的答案,下面的代码工作。

[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier]; 
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 

for (id obj in [cell.contentView subviews]) { 
    [obj removeFromSuperview]; 
} 

[cell.contentView addSubView:[self.arrayOfItems objectAtIndex:indexPath.row]; 

回答

0

添加对象之前添加此行cell.contentView

for (id obj in [cell.contentView subviews]) { 
    [obj removeFromSuperview]; 
} 

然后在cell.contentView添加您的物体,像下面

[cell.contentView addSubView:[self.arrayOfItems objectAtIndex:indexPath.row]; 

,可以帮助您。

+0

谢谢。这工作,但我不得不稍微修改我的代码的其余部分。 – user2970395

0

给标签的子视图,并删除它,如果电池被重用:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:@"MyIdentifier"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
} 
else 
{ 
    UiView* view = [cell viewWithTag:1907]; 
    [view removeFromSuperView]; 
} 
    UiView* view = [self.arrayOfItems objectAtIndex:indexPath.row]; 
    view.tag = 1907; 
    [cell addSubView:view]; 

    return cell; 
} 
1

我想你应该自定义两种不同的UITableView细胞。

CellForRowAtIndexPath

NSInteger row = indexPath.row; 
if(row%2 ==0){ 
    // register your UITextField cell 
}else{ 
    // register your UIImage View cell 
} 

我认为这是一个更好的方式来做到这一点。

0

您可以随时初始化tableviewcell。这将清除/刷新单元格。

用途:

UITableViewCell *cell = cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:@"MyIdentifier"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 

相反的:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 
if (cell == nil) { 
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle  reuseIdentifier:@"MyIdentifier"]; 
    cell.selectionStyle = UITableViewCellSelectionStyleNone; 
} 

我希望这会工作。