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
:
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
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.
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.