为什么当我的UITableView尝试加载时出现无法出队的错误?
我得到以下错误:
*由于未捕获的exception“NSInternalInconsistencyException”而终止应用程序,原因:'无法使用标识符FontCell出列单元 – 必须为该标识符注册一个nib或一个类,或者在故事板中连接一个原型单元格'
我不确定我做错了什么。 我设置了单元格标识符(以编程方式,因为它不是通过Interface Builder创build的),并且尽我所能在委托方法中做了所有事情,但是当我试图加载UITableView时,我仍然遇到了这个错误。
这里是相关的代码(值得注意的是我已经为自定义选项分类了UITableViewCell):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.fonts.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"FontCell"; FontCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; if (!cell) { cell = [[FontCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FontCell"]; cell.selectionStyle = UITableViewCellSelectionStyleNone; } int row = indexPath.row; cell.fontFamilyLabel.text = self.fonts[row]; return cell; }
这是我在我的子类UITableViewCell(FontCell)中改变的唯一方法:
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { self.fontFamilyLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 200, 20)]; self.fontFamilyLabel.textAlignment = NSTextAlignmentCenter; [self.contentView addSubview:self.fontFamilyLabel]; } return self; }
我究竟做错了什么?
最简单的修复方法是将其更改为FontCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
和你当前的代码一样,如果你使用这个方法,你必须检查确定cell
不是nil
。
或者,您可以在与@"FontCell"
绑定的表级别注册一个UINib
或Class
,
例如(在viewDidLoad
):
[self.tableView registerClass: [FontCell class] forCellReuseIdentifier:@"FontCell"];
那你可以做
FontCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FontCell" forIndexPath:indexPath];
这种方法的好处是,你知道你的单元不会是nil
,所以你可以立即开始修改它。
您正在使用dequeueReusableCellWithIdentifier:forIndexPath:
方法。 该方法的文档说明了这一点:
You must register a class or nib file using the registerNib:forCellReuseIdentifier: or registerClass:forCellReuseIdentifier: method before calling this method.
所以在这里
[self.tableView registerClass: [FontCell class] forReuseIdentifier: @"FontCell"];
我也有这样的问题,我find的解决scheme是:
转到Project Navigator并select“ViewController.h”。 附加
<UITableViewDelegate, UITableViewDataSource>
在“UIViewController”之后。
如果像我一样使用tableview(而不是一个表视图控制器),默认情况下没有出现单元格。
在故事板中selecttableview打开“属性”检查器将原型单元格从0更改为1select新显示的表格单元在“属性”检查器中将“标识符”设置为“FontCell”