2012-11-14 66 views
9

我正在使用重用標識以編程方式創建單元dequeueReusableCellWithIdentifier總是返回零(不使用故事板)

注意 - 我不使用故事板創建細胞

每當電池出列,細胞是零,所以細胞需要使用頁頭,這是昂貴的是新創建的。

編輯(添加1分更多的問題和糾正碼)

問題

  • 爲什麼這個離隊總是返回零?我該如何糾正它?
  • 僅當與故事板/筆尖文件一起使用時,是否允許出列作品?

代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if(!cell) //Every time cell is nil, dequeue not working 
    { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

    } 

    return cell; 
} 
+2

多久正是它返回零?您的設備屏幕上同時顯示了多少個這些單元格?重用意味着重新使用這些細胞,只是從屏幕上滾動出來。 –

+0

斯里卡爾是對的。必須在新創建的單元格上設置適當的單元標識符。 –

+0

它總是返回零。 4個單元格顯示在給定的時間,當我滾動出列返回nil。 – user1046037

回答

11

我做了幾個錯誤:

  1. 我用的UITableViewController一個子類,但創造的tableView子類的外
  2. 沒有在表視圖中創建一個tableView控制器,它是self.tableView在tableview控制器中,當返回索引路徑的單元格時,我使用的是self.tableView而不是tableView
  3. 此外,確保作爲static

    static NSString *CellIdentifier = @"Cell"; 
    
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    

由於tableViewself.tableView分別代表不同的表,所述小區標識符被聲明,細胞沒有被從同一個表中出列並且因此總是nil

+0

第3點是我的情況,現在已解決。謝謝 – NeverHopeless

+0

要點2.爲了徹底消除歧義,我將'nib'中的'tableView'命名爲'mTableView'。 – Jacksonkr

11

您需要先設置CellIdentifierCell。你在做那個嗎?當你創建一個新單元時,你需要爲它分配這個標識符Cell。只有那時iOS才能使用該標識符dequeueReusableCellWithIdentifier。通過編程,你可以像這樣 -

UITableViewCell *cell = [[UItableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"]; 

您可以從Interface Builder中集標識符太 -

enter image description here

+1

我不使用故事板,我以編程方式創建單元格。所以我不認爲這個解決方案可能適用。糾正我,如果我錯了 – user1046037

+0

嘿,我提供了兩個解決方案。請正確閱讀答案。首先我給出了程序化解決方案,然後爲了完整起見也提供了IB解決方案。 –

+0

我們對此深感抱歉,NSString的CellIdentifier設置爲@「細胞」。請注意,原始代碼現在已更新。我正在這樣做,它存在於我已粘貼的代碼中。你能否讓我知道我是否缺少一些東西。還是行不通。 – user1046037

2

此代碼應生成警告「控制到達非void函數結束」因爲你實際上沒有返回任何東西。將return cell;添加到該函數的末尾。此外,您永遠不會將重用標識符添加到新創建的單元格。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"Cell";  
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if(cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    return cell; 
} 
+0

粘貼代碼時,我錯過了幾行,現在我已經編輯和更新。你粘貼的代碼就是我正在使用的代碼。但每次都返回零。 – user1046037

1

首先聲明小區標識符 for tableViewCell at viewDidLoad方法爲:

[tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"MyCell"]; 

現在回憶起的UITableViewCell的實例具有相同標識符「了myCell」爲:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath]; 

此外只是填滿細胞。現在邏輯執行該數量有限細胞能夠有效地顯示巨大的列表(使用出列概念)。

但要記住分配值(甚至爲零如果需要的話),以在小區中使用的每一個的UIView,文本的改寫,否則/重疊/圖像會發生。

+0

這實際上是正確的答案 – SomaMan