首页 > 解决方案 > 编码时,我得到 Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value any solutions

问题描述

我对 iOS 相当陌生,我正在尝试制作一个表格视图控制器。编码时,我在标题中收到错误消息。很明显,我做错了什么。有人可以向我解释我做错了什么。我将在下面留下我的代码。

请注意,我没有使用情节提要。

class settingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    let elements = ["horse", "cat", "dog", "potato","horse", "cat", "dog", "potato","horse", "cat", "dog", "potato"]

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        // Error is on the following line
        tableView.delegate = self
        tableView.dataSource = self

        super.viewDidLoad()
    }

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

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell

        cell.cellView.layer.cornerRadius = cell.cellView.frame.height / 2

        cell.animalLbl.text = elements[indexPath.row]
        cell.animalImage.image = UIImage(named: elements[indexPath.row])
        cell.animalImage.layer.cornerRadius = cell.animalImage.frame.height / 2

        return cell
    }
}

标签: iosswiftuitableview

解决方案


您声明您没有使用故事板,但您已将您的tableView财产声明为插座。不要那样做。插座仅用于故事板。

您永远不会真正创建 a 的实例UITableView并将其分配给您的tableView属性。这就是为什么在尝试访问隐式展开的可选选项时会崩溃的原因nil

你还有一个UIViewController. 为什么不使用 aUITableViewController并节省大量工作?

您还需要注册您的自定义单元类。

另请注意,以大写字母开头的类、结构和枚举名称是标准的。变量、函数和案例名称以小写字母开头。

您的代码应该是:

class SettingsViewController: UITableViewController {
    let elements = ["horse", "cat", "dog", "potato","horse", "cat", "dog", "potato","horse", "cat", "dog", "potato"]

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(CustomTableViewCell.self, forCellReuseIdentifier: "customCell")
    }

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

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! CustomTableViewCell

        cell.cellView.layer.cornerRadius = cell.cellView.frame.height / 2

        cell.animalLbl.text = elements[indexPath.row]
        cell.animalImage.image = UIImage(named: elements[indexPath.row])
        cell.animalImage.layer.cornerRadius = cell.animalImage.frame.height / 2

        return cell
    }
}

要考虑的另一件事。由于您使所有行的高度相同,因此删除该heightForRowAt方法的实现并将以下行添加到viewDidLoad

tableView.rowHeight = 100

推荐阅读