如何在加载数据后安全地展开 table 视图单元格

how to safely unwrap table view cell after the data is loaded

这是我的 ViewController.swift 注释,在出错的行上有注释。

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var sections: [Section] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        SectionsData().getSectionsFromData({
            sections in

            self.sections = sections

            self.tableView.reloadData()
        })
    }
...
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // Next line errors out: unexpectedly found nil while unwrapping an Optional value
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCell

        cell.titleLabel!.text = sections[indexPath.section].objects[indexPath.row].name
        cell.datetimeLabel!.text = sections[indexPath.section].objects[indexPath.row].date

        return cell
    }
...

TableViewCell.swift,样式为Custom,单元格标识符为cell

import UIKit

class TableViewCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var datetimeLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

所以 tableView.cellForRowAtIndexPath(indexPath) 给出 nil 可能是因为数据尚未准备好显示。我该如何解决这个问题?

这实际上不是展开问题。您不小心使用了 cellForRowAtIndexPath 而不是 dequeueReusableCellWithIdentifier:indexPath.

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as? TableViewCell

正如 @Eendje 所指出的,确保您在 Interface Builder 中注册了您的单元格标识符。只需查看您的故事板,单击单元格并在 Interface Builder 中更新您的标识符。