没有Storyboard的Swift UITableViewCell不使用自动布局

时间:2018-05-08 08:47:40

标签: ios swift uitableview autolayout

我正在尝试编写一个没有Storyboard的UITableViewController和一个定义UITableViewCell的类。
我按照

的要求配置了表格视图
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200.0  
tableView.register(HomeCell.self, forCellReuseIdentifier: "cell")

并创建了一个只有图标的HomeCell UITableViewCell类。

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

    icon = UIImageView(frame: CGRect.zero);
    icon.translatesAutoresizingMaskIntoConstraints = false;
    contentView.addSubview(icon)
}

我在类中插入了自动布局的func,并通过调试控制了该函数的调用:

override func layoutSubviews() {
    icon.heightAnchor.constraint(equalToConstant: 50).isActive = true
    icon.widthAnchor.constraint(equalToConstant: 50).isActive = true
    icon.leftAnchor.constraint(equalTo: contentView.leftAnchor,
                               constant: 5).isActive = true
    icon.topAnchor.constraint(equalTo: contentView.topAnchor,
                              constant: 5).isActive = true
    contentView.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5).isActive = true
} 

结果是我的图标位置正确,但contentView的高度错误,即UITableViewAutomaticDimension设置的原始尺寸为44,并且连续的行重叠。
有人知道出了什么问题吗?

1 个答案:

答案 0 :(得分:0)

您应该激活约束a

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

    icon = UIImageView(frame: CGRect.zero);
    icon.translatesAutoresizingMaskIntoConstraints = false;
    contentView.addSubview(icon)
    setContr()
} 
func setContr() {

    icon.heightAnchor.constraint(equalToConstant: 50).isActive = true
    icon.widthAnchor.constraint(equalToConstant: 50).isActive = true
    icon.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 5).isActive = true
    icon.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 5).isActive = true
    contentView.bottomAnchor.constraint(equalTo: icon.bottomAnchor, constant: 5).isActive = true
}