【发布时间】:2019-04-15 18:24:24
【问题描述】:
我有一个 NSArray(称为 masterArray),其中包含 2 种不同类型的对象 - object1 和 object2。这些对象需要 2 个不同的表格视图单元格(每个都是以编程方式制作的),我是这样实现的
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[masterArray objectAtIndex:indexPath.row] isKindOfClass:[object1 class]])
{
cell1 *cell = (cell1 *)[tableView dequeueReusableCellWithIdentifier:@"obj1Cell"];
if (cell == nil)
{
cell = [[cell1 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"obj1Cell"];
}
//set up labels and stuff
return cell;
}
if ([[masterArray objectAtIndex:indexPath.row] isKindOfClass:[object2 class]])
{
cell2 *cell = (cell2 *)[tableView dequeueReusableCellWithIdentifier:@"obj2Cell"];
if (cell == nil)
{
cell = [[cell2 alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"obj2Cell"];
}
//set up labels and stuff
return cell;
}
return nil;
}
现在,这段代码可以很好地显示单元格。当您点击一个单元格时,我使用此代码:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
newViewController *newVC = [[newViewController alloc]init];
newVC.item = [masterArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:newVC animated:YES];
}
但是,当我点击时,我收到错误消息“UITableView 无法从其数据源获取单元格”。我也看过其他回答这个问题的问题。 This one 表示要添加行
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
所以我这样做了,用
替换我的“cell1 *cell = (cell1 *)...”行cell1 *cell = (cell1 *)[tableView dequeueReusableCellWithIdentifier:@"obj1Cell" forIndexPath:indexPath];
现在我得到了一个
"'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier obj1cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard"
错误,这不适用于我的情况,因为我的 UITableViewCells 是以编程方式制作的(没有情节提要)。在那篇文章中还建议添加“UITableViewDelegate,UITableViewDataSource”,但这似乎只是 Swift 中的一个选项,而不是 Objective-C。
【问题讨论】: