我有一个显示在 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];
}
最佳答案
你的代码有问题。您正在使用可重用的单元格,问题是您没有重新使用单元格内的 View 。特别是时间标签。每次使用单元格时,您都会创建一个新的时间标签,当您重复使用一个单元格时,您会向单元格添加一个附加标签,这就是重叠文本的可能原因。
为了重复使用标签,您应该为 UILabel 设置一个 TAG 编号,并在创建新的 uilabel 之前检查单元格是否已经有一个 TAG 编号。
我将替换代码:
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 为例。祝你好运!
关于objective-c - 单击 uitableview 单元格后获取相同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10123302/