As far as I can tell, I have set up everything correctly (register and dequeue). However, when I try and access outlets in awakeFromNib(), I get
‘Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file ….MechEntryCell.swift, line 18’
Which is weird, since other UITableViewCells doing similar things seem to work fine – and look identical to me.
The code failing:
class MechEntryCell: UITableViewCell {
@IBOutlet weak var mechName: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
mechName.text = "Hello" <<<<<<< CRASHES
}
func setDamageOption(_ damageOption: AdditionalDamageOption) {
mechName.font = UIFont.boldSystemFont(ofSize: mechName.font.pointSize)
mechName.text = damageOption.label <<<< WORKS FINE IF ABOVE CRASH REMOVED
}
}
which has a .xib file where the label has been correctly linked:
And I also register and dequeue:
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.register(UINib(nibName: MechEntryCell, bundle: nil), forCellReuseIdentifier: "MechEntryCell")
........
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tempDamageOptions.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: MechEntryCell.identifier) as? MechEntryCell {
cell.setDamageOption(tempDamageOptions[indexPath.item])
return cell
}
return UITableViewCell()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
Special Note:
When I set the label in the tableView(cellforRowAt:) method, then it works fine – so the IBOutlet DOES eventually link. What am I doing wrong?
2
Answers
I come back in shame with the solution.
somewhere during setup, I accidentally set the root view's custom class to that of the MechEntryCell. Removing this solved the issue.
Just want to add another example that might easily/accidentally happen to someone. In this case, had accidentally put the cell class on the ContentView, (rather then should have been left as simply UIView). In code, the cell’s awakeFromNib was getting called twice. The first time the outlets were set, and in the second mysterious call, the outlets were nil.