我有和在uitableview中显示的字符串数组。当用户点击排序按钮时,数组被排序,然后我使用[tableview reloaddata]。这样新的排序内容就会显示在表格中。但是当我选择特定的单元格时,单元格显示两个相互重叠的文本,新的排序文本和之前存在于该单元格中的文本。为什么会这样。
这是我显示单元格的代码。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
UILabel * timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(190, 0, 120, tableView.rowHeight)];
timeLabel.text = [[dataArray objectAtIndex:indexPath.row] time];
[cell.contentView addSubview:timeLabel];
return cell ;
}
这是我的排序代码。
-(void)sortByTime{
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time"
ascending:NO] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
dataArray = [sql getTableData]; // get data from sql file
sortedArray = [dataArray sortedArrayUsingDescriptors:sortDescriptors];
dataArray = [[NSMutableArray alloc]initWithArray:sortedArray];
[dataTableView reloadData];
}
答案 0 :(得分:1)
您的代码中存在问题。您正在使用可重用的单元格,问题是您没有重新使用单元格内的视图。特别是,timeLabel。您每次使用单元格时都会创建一个新的timeLabel,当您重复使用单元格时,您会在单元格中添加一个adicional标签,这可能是出现过度文本的原因。
为了重复使用标签,您应该为UILabel设置一个TAG编号,在创建新的uilabel之前,检查该单元是否已经有一个。
我会替换代码:
UILabel * timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(190, 0, 120, tableView.rowHeight)];
timeLabel.text = [[dataArray objectAtIndex:indexPath.row] time];
[cell.contentView addSubview:timeLabel];
使用:
UILabel * timeLabel = [cell viewWithTag:55]
if(!timeLabel) {
timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(190, 0, 120, tableView.rowHeight)];
timeLabel.tag = 55;
[cell.contentView addSubview:timeLabel];
}
timeLabel.text = [[dataArray objectAtIndex:indexPath.row] time];
标签号的值取决于您,我只使用55作为示例。祝你好运!
答案 1 :(得分:0)
因为你想要一个自定义的单元格,并且每次发生这种情况时你只需要在单元格中放置新的子视图,你必须使用在不同的笔尖中创建的自定义单元格并用它来显示你的数据
只需创建新的笔尖并从新笔尖加载它,这样就可以获得正确的数据
或者可以检查单元格内容中是否有任何子视图然后先删除它们然后添加新创建的子视图