我想在图像高度的情况下在我的UITableView
中制作动态单元格。一切工作正常,但是当我滚动我的UITableView
时,调试器在我的单元中对我的坏约束大喊大叫,但单元格看起来正是我想要的。当我看到这个调试信息我无法平静;)更新UITableViewCell中的约束不正确
我CustomCell
类看起来像:
class CustomCell: UITableViewCell {
//MARK: - Outlets
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var heightConstraint: NSLayoutConstraint!
//MARK: - Variables
var dream: MyDream? {
didSet {
if let item = dream, let image = UIImage(data: item.photoData) {
scaleImageView(image: image)
photoImageView.image = image
titleLabel.text = item.title
}
}
}
func scaleImageView(image: UIImage) {
let imageWidth = image.size.width
let imageScale = image.size.height/image.size.width
if imageWidth > photoImageView.bounds.width {
heightConstraint.constant = photoImageView.bounds.size.width * imageScale
} else {
heightConstraint.constant = imageWidth * imageScale
}
}
}
我在.xib
细胞看起来像这样:
TitleLabel
doesn't have a height constraint. Leading, Top, Trailing, Bottom only.
和我的ViewController
很简单,看起来像这样:
class ViewController: UIViewController {
//MARK: - Outlets
@IBOutlet var tableView: UITableView!
//MARK: - Variables
lazy var dreams = [MyDream]()
override func viewDidLoad() {
super.viewDidLoad()
createModel() // I mock data here :)
setTableView()
}
func setTableView() {
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
tableView.register(UINib(nibName: String(describing: CustomCell.self), bundle: nil), forCellReuseIdentifier: "cell")
}
func createModel() {
for i in 0..<12 {
if i < 6 {
if let image = UIImage(named: "\(i + 1)"), let imageData = UIImageJPEGRepresentation(image, 100) {
let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
dreams.append(dream)
}
} else {
if let image = UIImage(named: "\(i - 5)"), let imageData = UIImageJPEGRepresentation(image, 100) {
let dream = MyDream(photoData: imageData, title: "Image number \(i + 1)")
dreams.append(dream)
}
}
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dreams.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
cell.dream = dreams[indexPath.row]
cell.selectionStyle = .none
return cell
}
}
它看起来像在模拟器:
每一件事情看起来不错,但控制台给了我这样那样的错误:
我不知道为什么?我试图在CustomCell
中使用layoutIfNeeded()
,updateConstraints()
和setNeedsLayout()
中的didSet
,但没有帮助。有什么建议么?
您是否已经为tableview中的行设置了估计的高度或实现了'estimatedHeightForRow(at:)'函数? – Paulw11
他设置了'estimatedRowHeight',并使用了'UITableViewAutomaticDimension'的'rowHeight',这是所有必要的。这种关于“封装布局高度”的警告可以通过将您的一个垂直约束从1000降低到999来解决,这样可以防止出现错误,但高度可以正确计算。例如。 https://stackoverflow.com/q/25059443/1271826。搜索“UIView-Encapsulated-Layout-Height”,你会看到很多关于这个主题的讨论。 – Rob