当前位置:  开发笔记 > IOS > 正文

无法从其DataSource获取单元格

如何解决《无法从其DataSource获取单元格》经验,为你挑选了3个好方法。

以下代码有什么问题

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

    NSString *CellIdentifier  = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    cell.textLabel.text = @"hello";

    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 2;
}

但我无法从其dataSource获取一个单元格

整个例外是

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UITableView (; layer = ; contentOffset: {0, 0}; contentSize: {414, 88}>) failed to obtain a cell from its dataSource ()'

我为表视图设置了委托和数据源



1> 小智..:

使用Swift 3我忘记将UITableViewDataSource和UITableViewDelegate协议添加到ViewController声明时遇到此错误.

class DataViewController:UIViewController,UITableViewDataSource,UITableViewDelegate

添加它们解决了问题.



2> TwoStraws..:

您的错误表明由于某种原因cellForRowAtIndexPath返回nil,我猜这是因为您未能将可重复使用的单元格出列.如果你想确认这一点,只需在当前的出列呼叫后设置一个断点:我希望你能找到cell设置为nil.

如果您正在使用现代Xcode模板,您可以获得为您制作的原型单元,那么您应该使用它:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

如果您没有使用Xcode模板,请使用该行代码,然后注册您自己的重用标识符,如下所示:

[self.tableView registerClass:[UITableViewCell self] forCellReuseIdentifier:@"Cell"];

一切都很好,应该解决问题.我为Swift用户更详细地写了这篇文章.



3> Vivek..:
Swift 3.0

您只需要添加UITableViewDelegateUITableViewDataSource

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

下图仅供参考.

在此输入图像描述

推荐阅读
mobiledu2402851377
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有