【问题标题】:iOS: UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath:iOS:UITableView 数据源必须从 tableView:cellForRowAtIndexPath 返回一个单元格:
【发布时间】:2012-07-27 00:08:03
【问题描述】:

我检查了其他几个问题,但仍然无法弄清楚为什么会发生这种情况。我所知道的是在使用来自this 问题的描述代码之后,单元格的值是null。我已经正确设置了tabledelegatedatasource,但我看不出哪里出了问题。

如果我将以下方法的返回值设置为 0,则不会发生错误,因为 cellForRowAtIndexPath 方法并没有真正发生。因此,如果我将其设置为 1(应该如此),它将引发错误。我已经合成了NSArray 并检查了它是否已填充(尽管我猜这不重要),基本上意味着我按下一个button 进行搜索,然后将结果放在table 中。所以在此之前tableview 是空的。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

这是cellForRowAtIndexPath 方法本身。我也尝试过使用基本模板方法,但仍然抛出相同的错误。

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
    {
        static NSString *CellIdentifier = @"Cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...

    NSDictionary *aResult = [results objectAtIndex:[indexPath row]];
    NSLog(@"RESULTS IN TABLE %i", [results count ]);


    id key = [results objectAtIndex:[indexPath row]];
    resultTitle.text=@"Hello";

    NSURL *url = [NSURL URLWithString:[aResult objectForKey:@"url"]];
    NSData *data = [NSData dataWithContentsOfURL:url];
    cell.imageView.image = [UIImage imageWithData:data];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [theTableView reloadData];

    return cell;
}

我不知道出了什么问题。我之前使用过tableviews,并将这个项目与其他项目进行了比较,看看我是否遗漏了什么,但我看不出任何真正的差异。

【问题讨论】:

    标签: ios datasource tableview


    【解决方案1】:

    您没有返回第 0 节中的行数的方法 - 这是必需的数据源方法(在这种情况下)。

    【讨论】:

      【解决方案2】:

      如果从 dequeue 方法返回 nil,则您没有初始化单元格

      改变

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      

      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
      if (!cell)
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      

      【讨论】:

      • 太好了,解决了。描述不再为空,所以我现在可以开始格式化单元格。谢谢,我会在一分钟内接受答案。
      • @Stavash 不正确,将有一种新方法可以使单元格出列,但当前方法仍然存在
      • 仅供参考 - 使用 Storyboards 和 iOS5+ 保证 [tableView dequeueReusableCellWithIdentifier:CellIdentifier] 总是返回一个单元格
      • @Stavash 不完全是。我认为我们不能因为 NDA 而提及方法,但是 dequeueReusableCellWithIdentifier: 的行为在 iOS6 下没有改变,但是有一个具有不同行为的新方法
      猜你喜欢
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-06
      • 2011-10-09
      相关资源
      最近更新 更多