"无法获得一个小区"尝试使用UITableView时出错

时间:2016-11-20 13:35:33

标签: ios swift uitableview syntax-error swift3

我尝试使用以下代码返回表中的行数:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let count = FirstTableArray.count
    print(count)//prints 5
    return count
}

它无法发挥以下错误

  

2016-11-20 13:28:46.787 ModularProject [10870:2357799] *断言失败 - [UITableView _configureCellForDisplay:forIndexPath:],/ BuildRoot / Library / Cache / com.apple.xbs / Sources / UIKit_Sim / UIKit的-3600.5.2 / UITableView.m:8035   2016-11-20 13:28:46.829 ModularProject [10870:2357799] * 由于未捕获的异常终止应用程序' NSInternalInconsistencyException',原因:' UITableView(; layer =; contentOffset: {0,-64}; contentSize:{375,44}>)无法从其dataSource()'

获取单元格

我无法解决原因,强制0作为返回变量有效但不是1 ???

编辑1:

这是我的cellForRowAt方法供参考

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    print("runs")
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    print("runs2")
    cell.textLabel?.text = "Foo"
    return cell
    print("runs3")
}

3 个答案:

答案 0 :(得分:0)

强制0有效,因为tableView认为它没有要显示的行,因此它不会尝试调用cellForRowAt方法。

因此,如果您想使用任何数字1或更大,则必须实施cellForRowAt所需的UITableViewDataSource。这是一个例子:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
    cell.textLabel?.text = "Foo"
    return cell
}

假设您正在使用故事板,请确保在代码中设置您的单元格标识符,我在示例中将其用作“单元格”,以匹配您在故事板中用作单元格标识符的任何内容

答案 1 :(得分:0)

首先检查您是否在

中将单元格设为nil
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
}

如果对象返回nil

let object = line. If the problem is that tableView.dequeueReusableCell(withIdentifier:) // check object here, if nil then 

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

let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

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

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")

一切都很好,应该解决问题。如果没有,请检查小区标识符是否正确:它" Cell"默认情况下,您可能已更改它。 tableView.dequeueReusableCell(withIdentifier:)失败时,这种拼写错误应该导致崩溃,但无论如何都值得检查。

让我知道这是否适合您。

答案 2 :(得分:-1)

您检查了您的代理人和DataSource吗?

self.tableView.delegate = self
self.tableVie.dataSource = self

不确定您是否知道但是您必须将协议放在班级中?

class MyClass: UIViewController, UITableViewDelegate, UITableViewDataSource {}