dequeueReusableCellWithIdentifier始终返回nil(不使用storyboard) [英] dequeueReusableCellWithIdentifier always returns nil (not using storyboard)

查看:114
本文介绍了dequeueReusableCellWithIdentifier始终返回nil(不使用storyboard)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用重用标识符创建单元格以编程方式

I am creating the cell programatically using the reuse identifier.

注意 - 我没有使用storyboard用于创建单元格

Note - I am not using storyboard for creating the cell

每当单元格出列时,单元格为零,因此需要使用alloc重新创建单元格,这很昂贵。

Whenever the cell is dequeued, the cell is nil, so the cell needs to be newly created using alloc, which is expensive.

编辑(增加1个问题和更正后的代码)

问题


  • 为什么这个出队总是返回nil?我该如何更正呢?

  • 只有在与storyboard / nib文件一起使用时才出列队列吗?

代码

- (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;
}


推荐答案

我做了几个错误:


  1. 我使用的是 UITableViewController 的子类,但是正在创建tableView子类之外

  2. 在表视图控制器中创建了一个 tableView ,它是 self.tableView 在返回索引路径的单元格的tableview控制器中,我使用 self.tableView 而不是 tableView

  3. 另外,请确保将单元格标识符声明为 static

  1. I was using a subclass of UITableViewController, but was creating the tableView outside of the subclass
  2. There is a tableView created in the table view controller, which is self.tableView In the tableview controller while returning the cell for index path, I was using self.tableView instead of tableView.
  3. Also, ensure that the cell identifier is declared as static

static NSString *CellIdentifier = @"Cell";

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


由于 tableView self.tableView 代表不同的表,单元格没有从同一个表中出列,因此总是 nil

Since tableView and self.tableView were representing different tables, the cell was not being dequeued from the same table and hence was always nil

这篇关于dequeueReusableCellWithIdentifier始终返回nil(不使用storyboard)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆