iphone - 自定义单元格 : fatal error: unexpectedly found nil while unwrapping an Optional value

标签 iphone ios7 swift

我有一个表格 View ,其中包含创建为 .xib 的自定义单元格。我没有使用 Storyboard。我有一个问题,我无法用来自 webservice 结果的数据填充我的表。此外,我在自定义单元格中有 4 个标签。在我的自定义单元格类中,当我尝试为每个项目设置标签时,它会给我如上所示的 fatal error 。

这是我的代码:

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
}
}

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

导入 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) + " $"
    }
}

我在“setCell”方法 block 中遇到错误。

我已经阅读了很多问题和解决方案,但我尝试了所有这些对我来说都不起作用。

感谢您的回答,

最好的问候。

解决方案: 我已通过将单元格项目链接到单元格自身而不是链接到文件所有者来解决此问题。这样做我的问题就解决了。

最佳答案

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

let nib = UINib(nibName: "YOUR_CUSTOM_CELL_NIB_NAME", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "YOUR_CUSTOM_CELL_ID")

关于iphone - 自定义单元格 : fatal error: unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25569516/

相关文章:

iphone - UIImageView _isResizable : Unrecognized Selector

iphone - IOS8应用程序支持IOS 7和IOS 6吗?

ios - 无法在 SpriteKit Swift 中使用 SKVideoNode 播放视频

ios - UIAccessibilityCustomAction 选择器不适用于静态方法

ios - 在按钮单击上生成文本字段 swift

swift - 按下按钮后使用 case 语句检查值的状态

iPhone:保存字符串列表以便用户下次打开应用程序时可用的选项有哪些?哪个选项最佳?

ios - CollectionView Cell 滑动执行操作

ios - 设置 AppleLanguages 在 iOS 7 上不起作用?

iphone - 在 Objective-c 中迭代类成员