[英]Duplicated data in the cells of a UITableview
當我在表格視圖中向上和向下滾動時,每個單元格中的數據變得重復且不可讀。 有沒有人對下面有任何建議?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateStyle:NSDateFormatterShortStyle];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 12, 250, 20)];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(250, 12, 50, 20)];
label1.tag= 666;
label2.tag= 666;
[cell.contentView addSubview:label1];
[cell.contentView addSubview:label2];
// Configure the cell...
President *p = (President *)[self.importedRows objectAtIndex:indexPath.row];
label1.text = p.no;
label2.text = p.name;
UILabel* cellLabel = (UILabel*)[cell viewWithTag: 666];
cellLabel.text = [NSString stringWithFormat:p.no , p.name];
return cell;
}
dequeueReusableCellWithIdentifier
緩存生成的單元格。 因此,如果您要求在此單元格之前創建的單元格不會從頭開始再次生成(意味着您之前添加的標簽已經存在!)。
因此,添加標簽時,請使用唯一編號標記它們:
label1.tag= 666;
label2.tag= 667;
在將它們添加到單元格之前,請按如下方式刪除它們:
UIView *labelView = [cell.contentView viewForTag:666];
if (labelView != nil) {
[labelView removeFromSuperView];
}
並對第二個標簽做同樣的事情。
因為您一次又一次地將label1和label2添加到單元格中。
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(10, 12, 250, 20)];
UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(250, 12, 50, 20)];
[cell.contentView addSubview:label1];
[cell.contentView addSubview:label2];
當細胞被重復使用時,相同的細胞被用於另一行,並且它已經具有label1,2。 但是你一次又一次地創建label1,2並將它們添加到它。
為label1,label2提供不同的標簽。檢查viewWithTag:666和667是否存在。如果不存在則將它們添加為子視圖,如果已存在,只需使用viewWithTag獲取它們並更改其文本值。
這里的問題是以下代碼:
UILabel* cellLabel = (UILabel*)[cell viewWithTag: 666];
cellLabel.text = [NSString stringWithFormat:p.no , p.name];
我已經嘗試過你的代碼,評論這兩行不再重疊。 您可以嘗試更改此標簽的框架。
我建議創建你自己的UITableViewCell的子類,它上面有兩個UILabel,然后在你上面使用的方法中,如果單元格不存在,則創建子類的實例而不是UITableViewCell,然后填充標簽。
在自定義單元格實現文件中,您必須覆蓋'prepareForReuse'方法,並在其中將標簽文本設置為nil(@“”)。 這正確地使用了'dequeueWithReuseIdentifier'功能,並且僅在必要時創建標簽,而不是僅在需要時顯示它們。
您可以獲得性能的解決方案如下。
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// create and add labels to the contentView
}
// retrieve and update the labels
顯然你也可以創建你的UITableViewCell
子類。
你也可以試試這個贓物(新鮮的答案,得到你的新答案!):
BOOL doesContain = [cell.subviews containsObject:imageView];
if (!doesContain)
{
[cell.contentView addSubview:imageView];
}
imageView.image = yourImage];
另外,為了快速地將所有內容子類化, 請檢查我的答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.