致命错误:在UITableViewCell中解包可选值时出现意外的nil
类似的问题被问到here但这并不能解决这个问题。我在ViewController
中添加了tableView
。使用它的dataSource和Delegate扩展了类,并为其添加了所需的方法。
然后我在此表(不为它的单独的.xib)制成的原型细胞和由类为该TableViewCell
并收集@IBOutlet
:致命错误:在UITableViewCell中解包可选值时出现意外的nil
@IBOutlet weak var titleOfAccount: UILabel!
@IBOutlet weak var lastModified: UILabel!
@IBOutlet weak var accountImage: UIImageView!
@IBOutlet weak var cellView: UIView!
然后,在表视图cellForRowAt
方法时,我写
cell.titleOfAccount.text = "Hello World"
cell.lastModified.text = "Last Modified: 21 May 2017"
并运行它崩溃的代码与此错误。
fatal error: unexpectedly found nil while unwrapping an Optional value
我搜索在这里和那里后,我才又回到tableViewCell
类,并改变!
到?
和更新代码cellForRowAt
为:
cell.titleOfAccount?.text = "Hello World"
cell.lastModified?.text = "Last Modified: 21 May 2017"
现在,当我运行该程序成功运行但在tableView
中没有出现细胞,我也实施了该方法:
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3;
}
以下是我的cellForRowAt
方法的完整代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: AccountsTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! AccountsTableViewCell
cell.backgroundColor = UIColor.clear
cell.clipsToBounds = true
cell.cellView.layer.shadowColor = UIColor.black.cgColor
cell.cellView.layer.shadowOpacity = 1
cell.cellView.layer.shadowOffset = CGSize.zero
cell.cellView.layer.shadowRadius = 10
cell.titleOfAccount.text = "Hello World"
cell.lastModified.text = "Last Modified: 21 May 2017"
cell.accountImage.image = UIImage(named: "fb")
return cell
}
P.S.我也viewDidLoad
从你viewDidLoad()
删除以下行(代码),因为你已经连接从故事板你的手机。
self.tableView.register(AccountsTableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
还为身份检查员(属性检查器的左侧)共享快照。
是的!我完全忘了这个... #SwiftBeginners –
加入self.tableView.register(AccountsTableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
试试这个
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "yourcellidentifier", for: indexPath) as! AccountsTableViewCell
// add your code
}
没有仍然相同:'致命错误:意外地发现零,而解包可选值' –
检查你的单元格标识符与故事板请它应该是“yourcellidentifier” –
刚刚检查它是相同的两端'accountCell' –
let cell = tableView.dequeueReusableCell(withIdentifier:cellReuseIdentifier,for:indexPath)as! AccountsTableViewCell –
nope仍然是相同的错误! –
如何声明可重用标识符? –