Сергей В
Сергей В

Reputation: 111

Set data in UITableViewCell

I try use UITableViewCell. My custom cell has StackView's and other views. I need to send object from controller (UITableViewController) for next parsing it. in cell I set field:

  class MyCell: UITableViewCell {

    var myObject : MyObject?



    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {

        super.init(style: style, reuseIdentifier: reuseIdentifier)

      in this I try get data from my object 



    }



}


    required init?(coder aDecoder: NSCoder) {

        fatalError("init(coder:) has not been implemented")

    }



    override func awakeFromNib() {

        super.awakeFromNib()

        // Initialization code

    }


}

and in my Controller I write:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        // create a new cell if needed or reuse an old one
        let cell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as MyCustomCell!

        cell.myObject  = self.arrayMyObjects[indexPath.row]

        return cell
    }

But everytime I have nil in my cell. Why?

Upvotes: 1

Views: 1394

Answers (1)

Craig Siemens
Craig Siemens

Reputation: 13266

In your cell init is to early to try and access myObject. You should use a didSet on the property to make the changes when it's assigned a new value.

var myObject : MyObject? {
    didSet {
        // Update your subviews here.
    }
}

Upvotes: 2

Related Questions