[英]App crashed on cell initialisation
This is the custom class for my cell: 这是我的单元格的自定义类:
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)
}
}
And here's the code from cellForRowAtIndexPath
: 这是来自
cellForRowAtIndexPath
的代码:
let cell = tableView.dequeueReusableCellWithIdentifier("showSug") as! showSugTableViewCell
return cell
The problem is that my app crashes on the cell initialisation, and the log says: 问题是我的应用程序在单元初始化时崩溃,日志显示:
fatal error: unexpectedly found nil while unwrapping an Optional value
致命错误:解开Optional值时意外发现nil
How can I solve this? 我该如何解决?
EDIT: 编辑:
I changed my code to this: 我将代码更改为此:
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!
However, the app now crashed on the return statement. 但是,该应用程序现在在return语句上崩溃了。
Try following case to confirm the issue - I strongly believe following 2 issues might be your problem 请尝试以下案例以确认问题-我坚信以下两个问题可能是您的问题
if let retCell = tableView.dequeueReusableCellWithIdentifier("showSug") {
if let cell = retCell as? showSugTableViewCell {
//use the cell object
}else {
//1. cell may not be of type showSugTableViewCell so filing t convert
//If it is the case check in identifier you set in nib
}
}else {
//2. tableView.dequeueReusableCellWithIdentifier may not be returning for "showSug"
//Check class type it return table cell
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.