Swift不能在自定义单元格中自动工作

时间:2018-09-06 17:17:56

标签: swift 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

}

不起作用2个底线。

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

我可以创建此非编程性的文件,并且需要此结果

enter image description here

3 个答案:

答案 0 :(得分:0)

您需要在单元格中添加约束:

底部,顶部,左侧,右侧 和高度(您可以大于> =还是小于<=)

还为clipToBounds = true添加image view

enter image description here

答案 1 :(得分:0)

尝试以下代码,我认为您缺少此代码

class TableViewController: UITableViewController {

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

答案 2 :(得分:0)

找到了解决方案!!!当添加约束时需要:使用self.contentView

MainImageView.leftAnchor.constraint(equalTo:self.leftAnchor,常量:间距* 5).isActive = true

只需更改为

MainImageView.leftAnchor.constraint(equalTo:self.contentView .leftAnchor,常量:间距* 5).isActive = true