我正在尝试编写一个没有 Storyboard 的 UITableViewController,其中包含一个定义 UITableViewCell 的类。
我根据需要配置了表格 View
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)
}
我在类中插入了自动布局的函数,并通过调试控制该函数的调用:
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,并且连续的行重叠。
有人知道出了什么问题吗?
最佳答案
您应该激活约束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
}
关于ios - 没有 Storyboard 的 Swift UITableViewCell 不使用自动布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50229549/