dequeueReusableCellWithIdentifier总是返回nil(不使用storyboard)
我正在使用重用标识符编程创build单元格。
注 – 我没有使用storyboard来创build单元格
无论何时出现单元,单元都是零,所以单元需要使用alloc创build,这很昂贵。
编辑(增加了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; }
您需要首先将CellIdentifier
设置为Cell
。 你在做什么? 当你创build一个新的单元格时,你需要为它指定这个标识符Cell
。 只有这样iOS才能够使用该标识符将dequeueReusableCellWithIdentifier
。 以编程方式,你可以像这样做 –
UITableViewCell *cell = [[UItableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"Cell"];
您也可以从Interface Builder中设置标识符 –
我犯了一些错误:
- 我使用的是
UITableViewController
的子类,但是在子类之外创build了tableView - 在表视图控制器中创build了一个
tableView
,它是self.tableView
在tableview控制器中返回索引path的单元格时,我使用self.tableView
而不是tableView
。 -
另外,确保将单元标识符声明为
static
static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
由于tableView
和self.tableView
代表不同的表格,单元格没有从同一个表中出列,因此总是nil
这段代码应该产生警告“控制达到非void函数的结束”,因为你实际上并没有返回任何东西。 添加return cell;
到函数的结尾。 此外,您永远不会将重用标识符添加到新创build的单元格。
- (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; }
首先在viewDidLoad方法中声明一个tableViewCell的单元格标识符为:
[tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"MyCell"];
现在回想一下具有相同标识符“MyCell”的UITableViewCell的实例:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
进一步填充单元格。现在逻辑执行,有限数量的单元格能够有效地显示巨大的列表(使用出列概念)。
但是要记住,要赋值给单元格中的每个UIView,否则会覆盖/重叠文本/图像。