【发布时间】:2015-11-15 20:57:53
【问题描述】:
这是我的单元格的自定义类:
class showSugTableViewCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: .Default, reuseIdentifier: "showSug")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
let categoryLbl = UILabel()
categoryLbl.frame = CGRectMake(20, 10, 100, 20)
categoryLbl.text = "Text"
contentView.addSubview(categoryLbl)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
}
这是来自cellForRowAtIndexPath的代码:
let cell = tableView.dequeueReusableCellWithIdentifier("showSug") as! showSugTableViewCell
return cell
问题是我的应用程序在单元初始化时崩溃,日志显示:
致命错误:在展开可选值时意外发现 nil
我该如何解决这个问题?
编辑:
我将代码更改为:
let cellTemp = self.sugTableView.dequeueReusableCellWithIdentifier("showSug")
var cell = cellTemp as? showSugTableViewCell!
if cell == nil {
self.sugTableView.registerNib(UINib(nibName: "showSugTableViewCell", bundle: nil), forCellReuseIdentifier: "showSug")
self.sugTableView.registerClass(showSugTableViewCell.classForCoder(), forCellReuseIdentifier: "showSug")
cell = showSugTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "showSug")
}
return cell!
但是,应用现在在 return 语句上崩溃了。
【问题讨论】:
-
首先告诉我们错误发生在哪一行!
-
我说它在单元初始化时崩溃了,即
let cell = tableView.dequeueReusableCellWithIdentifier("showSug") as! showSugTableViewCell -
好吧,确切地说:那不是初始化。您是否在 IB 中设置了自定义单元格以具有关联的
showSug标识符?您是否将该单元格的类设置为showSugTableViewCell。注意:类应以大写字母开头:ShowSugTableViewCell -
将赋值拆分为两个操作:
let cellTemp = tableView.dequeueReusableCellWithIdentifier("showSug")和let cell = cellTemp as! showSugTableViewCel,然后调试看看cellTemp的实际类型是什么。 -
是的,那么你错过了一些东西。查看this answer 了解如何为给定标识符注册您的单元格
标签: ios swift uitableview