Objective c 单击uitableview单元格后获取相同的数据

Objective c 单击uitableview单元格后获取相同的数据,objective-c,ios,cocoa-touch,ipad,uitableview,Objective C,Ios,Cocoa Touch,Ipad,Uitableview,我有一个字符串数组,它显示在uitableview中。当用户点击排序按钮时,数组被排序,然后我使用[tableview reloaddata]。以便在表中显示新排序的内容。但是,当我选择特定单元格时,单元格显示两个相互重叠的文本,新排序的文本和该单元格中以前存在的文本。为什么会发生这种情况 这是我显示单元格的代码 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath

我有一个字符串数组,它显示在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];

}

由于您需要一个自定义单元格,并且每次都在单元格中放置新的子视图,因此您必须使用在不同nib中创建的自定义单元格,并使用它来显示数据

只需创建新的nib并从新的nib加载它,就可以获得正确的数据


或者可以检查单元格的contentView中是否有任何子视图,然后首先删除它们,然后添加新创建的子视图。代码中存在问题。您使用的是可重用的单元格,问题是您没有重用单元格内的视图。特别是,时间标签。每次使用单元格时,您都会创建一个新的时间标签,当您重用一个单元格时,您会向单元格添加一个辅助标签,这可能是文本重叠的原因

要重用标签,应为UILabel设置标记号,在创建新的UILabel之前,请检查单元格是否已有标记号

我将替换代码:

UILabel * timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(190, 0, 120, tableView.rowHeight)];
timeLabel.text = [[dataArray objectAtIndex:indexPath.row] time];
[cell.contentView addSubview:timeLabel];
与:

标签号的值由您决定,我仅以55为例。祝你好运

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];