我有一个表格 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/