2012-04-12 32 views
0

我有和在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]; 

} 

回答

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作爲例子。祝你好運!

+0

謝謝,它的工作就像一個魅力..謝謝。 – 2012-04-12 12:38:58

0

,只要你想定製的電池,你只要每天這happend你必須使用在輸精管筆尖創建定製的電池,並用它來顯示您的數據時,提出了新的子視圖細胞

只是讓新筆尖和新的筆頭加載它,所以你得到了正確的數據

或可以檢查是否有細胞的內容查看任何子視圖,然後先刪除它們,然後添加新創建的子視圖

相關問題