2012-02-13 41 views
0

如何保護UITableViewCell的文本,UITableViewCell在滾動時被更改。保護UITableView滾動事件的cell.textLabel.text

static NSString *CellIdentifier = @"Cell"; 
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(indexPath.row != [destinationList count]) 
{ 
    if (cell == nil) 
    { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.customLable.text = @"MyCustomLabel"; 
else 
{ 
    if (cell == nil) 
    { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.textLabel.text = @"Static Text to be set"; 
    [cell.customLable removeFromSuperview]; 
} 

問題:我每次滾動的UITableView,@ 「要設置靜態文本」 會被覆蓋上@ 「MyCustomLabel」。

我該如何預防?我希望UITableView的所有單元通過Table的LifeTime保留它們的TextLabels。

回答

1

兩個可能的答案:

  1. 一般也沒關係。重複使用單元格是它應該如何工作的,你應該每次完全「重置」每個單元格。你不應該在小區中存儲狀態反正
  2. 自定義標籤創建一個新的reuseIdentifier,一個又一個的靜態文本
+0

但是,它改變了我的「MyCustomLabel」到「設置靜態文本「(這是另一個單元格的文本)。 – Krishna 2012-02-13 16:40:51

+0

是的,這就是應該發生的事情。它只發生在細胞不再可見時。你可以通過爲靜態單元使用不同的重用標識符來阻止它。正如我在答覆中所說的那樣。 – 2012-02-13 16:48:21

+0

什麼也沒有改變,即使在創建新的reuseIdentifier之後。 – Krishna 2012-02-13 17:10:12

1

他們都將保留其UILabels屬性,因爲細胞得到重用這就是爲什麼你使用:

[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

然而UITableView的使用延遲加載這意味着它僅保留在內存中可見UITableViewCells,因此,當您滾動現在看不見細胞得到重用,現在新的可見細胞與您不能再看到的UILabel具有相同的UILabel。這意味着每次只有少數的UITableViewCell被重用。

這就是爲什麼在該實例方法prepareforReuse討論的文檔UITableViewCell

如果一個UITableViewCell對象是可重複使用的,也就是說,它有一個複用標識符,該方法被調用時返回的對象之前從UITableView方法dequeueReusableCellWithIdentifier :.出於性能考慮,您應該只重置與內容無關的單元格屬性,例如,alpha,編輯和選擇狀態。 tableView:cellForRowAtIndexPath:中的表視圖委託在重用單元時應始終重置所有內容。如果單元對象沒有關聯的重用標識符,則不調用此方法。如果您重寫此方法,則必須確保調用超類實現。

0

您應該爲不同的單元格製作不同的標識符。 無論如何,在UITableView中存儲的東西是一種錯誤的方法,它只是顯示數據,而不是存儲。

0

爲什麼你刪除自定義標籤?只要刪除標籤的文字。

if(indexPath.row != [destinationList count]) 
{ 
    /* ... */ 
    cell.textLabel.text = @""; 
    cell.customLable.text = @"MyCustomLabel"; 
else 
{ 
    /* ... */ 
    cell.textLabel.text = @"Static Text to be set"; 
    cell.customLable.text = @""; 
} 

並確保標籤是透明的。

0

試試這個

static NSString *CellIdentifier = @"Cell"; 
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) 
{ 
    cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 
cell.textLabel.text = nil; 
cell.customLabel.text = nil; 
if(indexPath.row != [destinationList count]) 
{ 
    cell.customLable.text = @"MyCustomLabel"; 
} 
else 
{ 
    cell.textLabel.text = @"Static Text to be set"; 
}