Reputation: 3
xcode: 9.4.1
I'm creating a simple table view but I keep getting the same "Unexpectedly found nil while unwrapping an Optional value" error when it comes to set a value to a component in each cell.
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
}
}
I did name my custom cell "ConditionCell" and I did name the identified "conditionCell".
Here is my custom cell class. I did add the component(label) reference to the class. It looks like the custom view class is successfully loaded (not nil) however its component (label) is not.
import UIKit
class ConditionCell: UITableViewCell {
@IBOutlet weak var conditionLabel: UILabel!
func setCell(condition: Condition) {
print(conditionLabel)
conditionLabel.text = condition.name
}
}
Upvotes: 0
Views: 47
Reputation: 4886
The problem is with this line :
conditionTable.register(ConditionCell.self, forCellReuseIdentifier: "conditionCell")
It requires UINib
. Change it to:
conditionTable.register(UINib(nibName: "ConditionCell", bundle: nil), forCellReuseIdentifier: "conditionCell")
For more details check this :
Upvotes: 1