自定义单元格:致命错误:在展开可选值时意外发现为零 [英] Custom cell: fatal error: unexpectedly found nil while unwrapping an Optional value
问题描述
我有一个自定义单元格的表格视图,创建为.xib。我没有使用故事板。我有一个问题,我不能用来自webservice结果的数据填充我的表。另外,我在自定义单元格中有4个标签。在我的自定义单元格类中,当我尝试为每个项目设置标签时,它会给出我上面的致命错误。
I have a table view with custom cell that was created as .xib . I didnt use storyboard. I have a problem that I couldnt fill my table with the data which came from webservice result. Also, I have 4 labels in the custom cell. In my custom cell class, when I try to set labels for each items, It gives me fatal error like above.
这是我的代码:
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
}
}
我的自定义单元格类位于:
And my custom cell class is here :
import UIKit
import 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方法块中收到错误。
I am getting the error inside of "setCell" method block.
我已经阅读了很多问题和解决方案我尝试了所有这些对我不起作用。
I have read a lot of questions and solutions and I tried all of them it doesnt work for me.
感谢您的回答,
祝你好运。
解决方案:我已经通过将单元格项目链接到单元格来解决了这个问题是自己的,而不是链接到文件的所有者。我的问题就是这样做了。
SOLUTION: I've solved this problem by linking the cell items to cell's own instead of linking to File's Owner. My problem has gone by doing this.
推荐答案
你的单元格必须是零。
使用
tableView.dequeueReusableCellWithIdentifier("cell") as ItemManagementTVCell
可以返回nil。你应该使用:
Can return nil. You should use:
tableView.dequeueReusableCellWithIdentifier("cell" forIndexPath:indexPath) as ItemManagementTVCell
这样可以保证单元格不为零。
This way it guarantees cells is not nil.
编辑:也许你可以预防将if语句放在setCell中崩溃
Maybe you can prevent the crash by putting if statements inside "setCell"
if var itemName = self.lblItemName {
itemName.text = name
}
为你在其中设置的每个标签做这个并检查崩溃是否仍然发生。如果不是,你必须检查这些标签为什么是零。
Do that for every label you set inside it and check if the crash still happens. If it don't you must check why those labels are nil.
这篇关于自定义单元格:致命错误:在展开可选值时意外发现为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!