【问题标题】:App crashed on cell initialisation应用程序在单元初始化时崩溃
【发布时间】: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


【解决方案1】:

尝试以下案例来确认问题 - 我坚信以下 2 个问题可能是您的问题

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
}

【讨论】:

  • 我已经更新了我的答案 - 检查您的笔尖并确保您已按预期进行配置。
  • 请问您收到的是哪个错误(第 1 点或第 2 点)?
  • 您介意分享一下您是如何解决问题的吗?
  • 我在这里找到了解决方案:link
猜你喜欢
  • 2014-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-30
  • 2012-10-20
  • 2016-04-22
相关资源
最近更新 更多