Search code examples
iosswiftuitableviewuitextfieldtvos

SWIFT: UITableViewCell is initialised before its properties are set in UITableView


I have this UITableViewCell:

class TableViewCell3: UITableViewCell {
    var sectionLabel: String?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.setupLabel()
    }

    func setupLabel() {
        let myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
        // App crashes here because sectionLabel is nil
        myTextField.text = sectionLabel!
        self.contentView.addSubview(myTextField)
    }
}

As you see, I am trying to display a UITextField inside each UITableViewCell.
The property sectionLabel that I'm trying to display, is set inside the UITableView:

extension MoviesViewController5: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell =
            tableView.dequeueReusableCell(withIdentifier: "tableViewCell", for: indexPath) as? sectionTableCell2
            else {
                fatalError("Unable to create explore table view cell")}

        cell.sectionLabel = sectionsLabels![indexPath.row]
        return cell
    }
}

The problem is that the UITableViewCell gets initialised before the sectionLabel property is set.
So when I try to display it:

   myTextField.text = sectionLabel!

The app crashes since it's nil.
Yes, I do know that I should add nil check but that's not the point.
The POINT is how do display the UItextField AFTER the sectionLabel property is set.


Solution

  • Better just setup UITextfield in the initializer and set its text when the sectionLabel is updated.

    class TableViewCell3: UITableViewCell {
    
        private var myTextField: UITextField?
    
        var sectionLabel: String? {
            didSet {
                 self.myTextField?.text = self.sectionLabel
            }
        }
     
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            self.setupLabel()
        }
    
        func setupLabel() {
            myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 300.00, height: 30.00));
            self.contentView.addSubview(myTextField!)
        }
    }