dequeueReusableCellWithIdentifier始终返回nil(不使用storyboard) [英] dequeueReusableCellWithIdentifier always returns nil (not using 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;
}
推荐答案
我做了几个错误:
- 我使用的是
UITableViewController
的子类,但是正在创建tableView子类之外 - 在表视图控制器中创建了一个
tableView
,它是self.tableView
在返回索引路径的单元格的tableview控制器中,我使用self.tableView
而不是tableView
。 -
另外,请确保将单元格标识符声明为
static
- I was using a subclass of
UITableViewController
, but was creating the tableView outside of the subclass - There is a
tableView
created in the table view controller, which isself.tableView
In the tableview controller while returning the cell for index path, I was usingself.tableView
instead oftableView
. 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屋!