Search code examples
swiftcell

Swift Don't work auto heigh in custom cell


Just custom class for cell

class CarCell: UITableViewCell { 

override func layoutSubviews() {

    MainImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing * 5).isActive = true
    MainImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: spacing).isActive = true
    MainImageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -spacing * 5 ).isActive = true
    MainImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -spacing).isActive = true
    MainImageView.heightAnchor.constraint(equalTo: MainImageView.widthAnchor).isActive = true

}

don't work 2 bottom lines.

class TableViewController: UITableViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    self.tableView.register(CarCell.self, forCellReuseIdentifier: "CarCell")
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 44
}

enter image description here

I can create this non programmatic and I need this result

enter image description here


Solution

  • found a solution!!! when add constraints need to: use self.contentView

    MainImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: spacing * 5).isActive = true

    just change to

    MainImageView.leftAnchor.constraint(equalTo: self.contentView .leftAnchor, constant: spacing * 5).isActive = true