swift - 错误消息 "Unexpectedly found nil while unwrapping an Optional value"即使它的单元格不为零

标签 swift xcode

xcode: 9.4.1

我正在创建一个简单的表格 View ,但我总是得到相同的结果 “在展开可选值时意外发现 nil” 为每个单元格中的组件设置值时出错。

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

    @IBOutlet weak var conditionTable: UITableView!

    var conditions = [Condition]()

    override func viewDidLoad() {
        super.viewDidLoad()

        conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell")
        conditionTable.delegate = self
        conditionTable.dataSource = self
        setInitData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func setInitData() {
        conditions.append(Condition(name: "a"))
        conditions.append(Condition(name: "b"))
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return conditions.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell: ConditionCell = tableView.dequeueReusableCell(withIdentifier: "conditionCell") as? ConditionCell
            else {
                fatalError()
        }
        print(cell.conditionLabel.text)
//        cell.setCell(condition: conditions[indexPath.row])
        return cell
    }

}

我确实将我的自定义单元格命名为“ConditionCell”,并将已识别的“conditionCell”命名为“conditionCell”。

这是我的自定义单元类。 我确实将组件(标签)引用添加到类中。 看起来自定义 View 类已成功加载(不是零) 但是它的组件(标签)不是。

import UIKit

class ConditionCell: UITableViewCell {
    @IBOutlet weak var conditionLabel: UILabel!

    func setCell(condition: Condition) {
        print(conditionLabel)
        conditionLabel.text = condition.name
    }

}

最佳答案

问题出在这一行:

conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell")

它需要 UINib。将其更改为:

conditionTable.register(UINib(nibName: "ConditionCell", bundle: nil), forCellReuseIdentifier: "conditionCell")

有关详细信息,请查看:

关于swift - 错误消息 "Unexpectedly found nil while unwrapping an Optional value"即使它的单元格不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51551829/

相关文章:

ios - 由于空间不足,无法在 xcode 中找到配置文件

swift - 值替换后恢复字符串插值

ios - 如何在我的应用程序中保存表格 View 的数据?

ios - 为什么 Interface Builder 对象没有显示在屏幕上?

ios - 模拟器不可用 appcelerator studio

php - Swift - JSON 响应以\u201c 开头并以\u201d 结尾

swift - 不同的函数如何具有相同的名称?

iphone - 如何制作可在 iOS 5 至 7 上运行的 armv7 arm64 fat 二进制文件?

ios - 分组静态表后台问题

ios - 无法使用 Xcode 9 创建 git 存储库