gpt4 book ai didi

ios - 如何在加载数据后安全地解包 TableView 单元格

转载 作者:行者123 更新时间:2023-11-29 01:14:47 25 4
gpt4 key购买 nike

这是我的 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 中注册了您的单元格标识符。只需查看您的 Storyboard,单击单元格并在 Interface Builder 中更新您的标识符。

enter image description here

关于ios - 如何在加载数据后安全地解包 TableView 单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35330346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com