如果我不想在我的表格 View 中使用原型(prototype)单元格。在 cellForRowAtIndexPath 中,我是否仍需要在代码中提供单元标识符才能使单元出队?
我已经试过了,但是当 tableview 尝试填充时它会抛出一个运行时错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
它发生在这条线上:
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
我不确定要使用什么其他行来使单元格出队。
请您参考如下方法:
是的,你必须这样做,否则 swift 无法找出你想要dequeue 的对象类型,因此你得到了 nil 对象。
你应该使用 - dequeueReusableCellWithIdentifier:forIndexPath:
代替 - dequeueReusableCellWithIdentifier
这是因为第一个实际上返回 AnyObject 而没有 indexpath 的 dequeue 返回 AnyObject?
为了使您的代码正常工作,您可以将代码更改为 ...forIndexPath
或者这样做:
var cell: UITableViewCell?
if let cell = cell {
//dequeue here
} else {
cell = UITableViewCell(style: UITableViewCellStyle,
reuseIdentifier reuseIdentifier: String?) ...
}
//config cell
return cell
如果您喜欢在代码中完成所有事情,您需要像 Mert 建议的那样将您的 UITableViewCell 类注册到 tableView。
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier identifier: "Cell")
示例代码:
// I remove all other things, just focus on what you need
override func viewDidLoad() {
super.viewDidLoad()
table.delegate = self
table.dataSource = self
table.registerClass(UITableViewCell.self, forCellReuseIdentifier identifier: "Cell")
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
configureCell(cell, atIndexPath: indexPath)
return cell
}
