xcode: 9.4.1
我正在创建一个简单的表格 View ,但我总是得到相同的结果 “在展开可选值时意外发现 nil” 为每个单元格中的组件设置值时出错。
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var conditionTable: UITableView!
var conditions = [Condition]()
override func viewDidLoad() {
super.viewDidLoad()
conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell")
conditionTable.delegate = self
conditionTable.dataSource = self
setInitData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setInitData() {
conditions.append(Condition(name: "a"))
conditions.append(Condition(name: "b"))
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return conditions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell: ConditionCell = tableView.dequeueReusableCell(withIdentifier: "conditionCell") as? ConditionCell
else {
fatalError()
}
print(cell.conditionLabel.text)
// cell.setCell(condition: conditions[indexPath.row])
return cell
}
}
我确实将我的自定义单元格命名为“ConditionCell”,并将已识别的“conditionCell”命名为“conditionCell”。
这是我的自定义单元类。 我确实将组件(标签)引用添加到类中。 看起来自定义 View 类已成功加载(不是零) 但是它的组件(标签)不是。
import UIKit
class ConditionCell: UITableViewCell {
@IBOutlet weak var conditionLabel: UILabel!
func setCell(condition: Condition) {
print(conditionLabel)
conditionLabel.text = condition.name
}
}
最佳答案
问题出在这一行:
conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell")
它需要 UINib
。将其更改为:
conditionTable.register(UINib(nibName: "ConditionCell", bundle: nil), forCellReuseIdentifier: "conditionCell")
有关详细信息,请查看:
关于swift - 错误消息 "Unexpectedly found nil while unwrapping an Optional value"即使它的单元格不为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51551829/