2013-12-17 45 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; 
} 

我希望這會工作。