自定义单元格:致命错误:在解包可选值时意外发现为零

ser*_*sut 7 iphone ios7 swift

我有一个自定义单元格的表视图,创建为.xib.我没有使用故事板.我有一个问题,我无法用来自webservice结果的数据填充我的表.此外,我在自定义单元格中有4个标签.在我的自定义单元格类中,当我尝试为每个项目设置标签时,它会给出我上面的致命错误.

这是我的代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
...

func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
        let cell: ItemManagementTVCell = tableView?.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell

    if let ip = indexPath
    {
        let item: Item = self.itemList[indexPath.row] as Item
        cell.setCell(item.itemName, status: item.itemStatus, duration: item.itemDuration, price: item.itemPrice)
    }
    return cell
}
}
Run Code Online (Sandbox Code Playgroud)

我的自定义单元类在这里:

导入UIKit

class ItemManagementTVCell: UITableViewCell {

    @IBOutlet var lblItemName: UILabel!
    @IBOutlet var lblItemPrice: UILabel!
    @IBOutlet var lblItemDuration: UILabel!
    @IBOutlet var lblItemStatus: UILabel!

    override func awakeFromNib()
    {
        super.awakeFromNib()
    }

    override func setSelected(selected: Bool, animated: Bool)
    {
        super.setSelected(selected, animated: animated)
    }

    func setCell(name: String, status: Int, duration: Int, price: Int)
    {
        self.lblItemName.text     = name
        self.lblItemStatus.text   = String(status)
        self.lblItemDuration.text = "Duration: \(String(duration)) months"
        self.lblItemPrice.text    = String(price) + " $"
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到"setCell"方法块内的错误.

我已经阅读了很多问题和解决方案,我尝试了所有这些问题和解决方案.

谢谢您的回答,

最好的祝福.

解决方案:我已经通过将单元格项链接到单元格而不是链接到文件所有者来解决了这个问题.这样做我的问题已经消失了.

Law*_*iet 8

无需将单元项链接到单元所有者的另一个问题的解决方案:

let nib = UINib(nibName: "YOUR_CUSTOM_CELL_NIB_NAME", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "YOUR_CUSTOM_CELL_ID")
Run Code Online (Sandbox Code Playgroud)


Thi*_*aes 7

你的"细胞"必须是零.

运用

tableView.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell
Run Code Online (Sandbox Code Playgroud)

可以返回零.你应该使用:

tableView.dequeueReusableCellWithIdentifier("cell" forIndexPath:indexPath) as ItemManagementTVCell
Run Code Online (Sandbox Code Playgroud)

这样它保证细胞不是零.

编辑:也许你可以通过在"setCell"中放置if语句来防止崩溃

if var itemName = self.lblItemName {
    itemName.text = name
}
Run Code Online (Sandbox Code Playgroud)

为您在其中设置的每个标签执行此操作,并检查崩溃是否仍然发生.如果不是,你必须检查为什么这些标签是零.