UITableView数据源问题

时间:2014-10-20 14:02:50

标签: ios uitableview custom-cell

我正在尝试创建一个基本的自定义单元格,在我按照教程后,我遇到了这个问题。

reason: 'UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:'

- (NSInteger)numberOfSections;
{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [array1 count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MainCell";

CustomCell *customCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

/*if (! customCell) {
    NSArray *parts = [[NSBundle mainBundle] loadNibNamed:@"cell" owner:nil options:nil];
    customCell = [parts objectAtIndex:0];
}
*/

customCell.lblTime.text = [array1 objectAtIndex:indexPath.row];
customCell.lblEvent.text = [array2 objectAtIndex:indexPath.row];

return customCell;
}

此外,我已经在tableView上设置了Identity,但它仍然无效,我正在使用Storyboard。此外,我已将datasourcedelegate联系起来。请问我的问题在哪里?

5 个答案:

答案 0 :(得分:0)

您的自定义单元格是否继承自UITableViewCell?你能告诉我们你的自定义单元代码吗?您也可以尝试:

CustomCell *cell = [tableView dequeuReusableCellWithIdentifier:@"YourCellIdentifier" forIndexPath:indexPath];

答案 1 :(得分:0)

使用dequeueReusableCellWithIdentifier:forIndexPath:而非dequeueReusableCellWithIdentifier:,如果您查看文档,

for,

dequeueReusableCellWithIdentifier:forIndexPath
  

出于性能原因,通常应该使用表视图的数据源   在将单元格分配给其中的行时,重用UITableViewCell对象   tableView:cellForRowAtIndexPath:方法。表视图维护一个   数据源具有的UITableViewCell对象的队列或列表   标记为重用。何时从数据源对象中调用此方法   要求为表格视图提供新单元格。该方法出列   现有单元格(如果有)或基于该单元格创建新单元格   您之前注册的类或nib文件。

代表dequeueReusableCellWithIdentifier:

  

出于性能原因,通常应该使用表视图的数据源   在将单元格分配给其中的行时,重用UITableViewCell对象   tableView:cellForRowAtIndexPath:方法。表视图维护一个   数据源具有的UITableViewCell对象的队列或列表   标记为重用。何时从数据源对象中调用此方法   要求为表格视图提供新单元格。该方法出列   现有单元格(如果有单元格可用)或使用该单元格创建新单元格   您之前注册的类或nib文件。如果没有可用的单元格   为了重用而你没有注册一个类或nib文件,这个方法   返回nil。

注意“此方法返回nil”。

仅供参考,在您使用registerNib:forCellReuseIdentifier:

的方法之前,请不要忘记注册您的单元格Nib

由于您使用的是故事板,请确保故事板中的“重用标识符”以及用于创建单元格的“重用标识符”是相同的。

答案 2 :(得分:0)

第一个答案解决了您的错误:从故事板检查单元格标识符,它应该在标识符名称下,而不是恢复ID

第二个答案:您需要在填充cell.lblTime.text的地方放置一个断点,如果它是空的,请检查填充数组的位置并尝试理解它为空的原因。请填写免费提出进一步的问题。

答案 3 :(得分:0)

在第一次执行中,单元格为零。所以编写代码来初始化单元格。

-(UITableViewCell *)tableView : (UITableView *)tableView cellForRowAtIndexPath:  
   (NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"MainCell";

    CustomCell *cell = (CustomCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
       NSArray *parts = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:nil options:nil];
       cell = [parts objectAtIndex:0];
    }

    cell.lblTime.text = [array1 objectAtIndex:indexPath.row];
    cell.lblEvent.text = [array2 objectAtIndex:indexPath.row];

    return cell;
}

答案 4 :(得分:0)

如果您已在故事板中创建了表格视图,并且单元格也在其中,那么我认为您可能没有在故事板中设置单元格标识符。

将故事板单元格的重用标识符设置为“MainCell”

相关问题