2012-06-09 39 views
0

我有我目前出隊,像這樣3個自定義UITableViewCells一個UITableView:自定義的UITableViewCell不會離隊正確

if (indexPath.row == 0) { 
     static NSString *CellIdentifier = @"MyCell1"; 
     MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     } 
     return cell; 
    } 
    if (indexPath.row == 1) { 
     static NSString *CellIdentifier = @"MyCell2"; 
     MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     } 
     return cell; 
    } 
    if (indexPath.row == 2) { 
     static NSString *CellIdentifier = @"MyCell3"; 
     MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
     if (cell == nil) { 
      cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     } 
     return cell; 
    } 

我試圖這樣做多種方式,但問題是,即使我」 m仍然使用不同的標識符將它們全部排隊,當我滾動tableView時,有時候我的第一個單元出現在我的第三個單元的位置,反之亦然。似乎有一些奇怪的緩存正在進行。

有誰知道爲什麼?謝謝。

+0

如果從刪除「靜態」什麼單元格標識符聲明? –

+0

它沒有區別。在Apple文檔中,即使他們使用靜態NSString * CellIdentifier。 – VTS12

+0

儘管您應該有三個不同的標識符變量,因爲您有三個不同的值。靜態只能初始化一次。你在哪裏看到這個代碼實際上是在細胞中放入任何信息,你在哪裏做的?你能提供一個問題的截圖嗎?真的只有三排嗎? – jrturton

回答

1

由於您總是分配相同的單元類,因此您發佈的代碼沒有意義。單元格標識符不用於標識特定的單元格,而是用於您正在使用的子類。

所以更改代碼:

static NSString *CellIdentifier = @"MyCell"; 
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 
return cell; 

,並根據indexPath.section和indexPath.row在willDisplayCell正確設置單元格內容:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath 
+0

所以在willDisplayCell:forRowAtIndexPath:我應該改變/設置像自定義單元格標籤,編輯自定義單元格文本域等東西?我認爲根據蘋果文檔,你應該通過檢索子視圖標籤的視圖來做到這一點? – VTS12

+0

如果您要創建獨特的子視圖,請在cellForRowAtIndexPath中執行此操作,然後在willDisplayCell中設置值。在你發佈的代碼中,你所有的UITableViewCell都基本相同,沒有獨特的子視圖,所以不需要3個標識符。我通常做的是創建一個「fillCellWithData」方法,並從cellForIndexPath和willDisplayCell中調用它。 – EricS

+0

想象cellForIndexPath作爲創建視圖的方式,或者找到一個已經存在的willDisplayCell的未使用的視圖,因爲另一次你必須用數據填充它。 – EricS

相關問題