简体   繁体   中英

IBOutlet not accessible in awakeFromNib in UITableViewCell

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?

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. 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM