OGeek|极客世界-中国程序员成长平台

标题: ios - 无法将具有标识符标题的单元格出列 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 13:33
标题: ios - 无法将具有标识符标题的单元格出列

当我按下打开表格 View 的按钮时出现以下错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier title - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

这里是 tableview 的 View Controller 中的代码和导致问题的方法:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {

NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

return cell;
}

我研究了错误并尝试删除 forIndexPath:indexPath,因此代码如下所示:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {

NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

return cell;
}

现在这导致了一个新错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:

现在我做了一些日志记录,发现 cell == nil 是真的,所以我按照之前的一些问题的建议添加了一个检查:

- (UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath {

NSString *CellIdentifier = [menuItems objectAtIndex:indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
     cell = [[UITableViewCell alloc] init]
}

return cell;
}

现在这消除了所有错误,但是现在当我打开 tableview 时,当我想要在 Storyboard 中创建的单元格时,单元格是空的。

我该如何解决这个问题?

这是 Storyboard中 View Controller 的外观:



Best Answer-推荐答案


您可以在 UITable 上调用两种单元格回收方法 查看,

-(UITableViewCell *) dequeueReusableCellWithIdentifier:forIndexPath:
-(UITableViewCell *)dequeueReusableCellWithIdentifier:

这有点令人困惑,但它们的使用方式却大不相同。采用第二个参数(类型为 NSIndexPath)的参数取决于您首先使用 tableView 注册了一个类或 xib 文件,以便 tableView 可以在没有方便的时候为您创建一个临时单元格回收。第一种方法将始终返回一个单元格,因此您可以编写自己的 cellForRowAtIndexPath: 代码。

第二种方法(只接受一个参数, (NSString *)cellIdentifier 可以并且将在没有方便回收的单元格时返回 nil。因此,当您使用此方法时,您应该测试结果为 nil 并创建一个单元格在这种情况下。 例如

-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath{

  static NSString *cellId = @"cellID";

  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];

  if (!cell) {
    cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
  }

 //etc etc decorate your cell...

  return cell;
}

为了利用您的单元格原型(prototype),您需要为每一行/部分注册一个类或 xib,以便表格知道要创建哪个单元格。回收的东西只有在创建了足够的单元格来填满屏幕并且你开始滚动时才真正起作用。祝你好运

关于ios - 无法将具有标识符标题的单元格出列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768917/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4