我有一个表格 View ,我使用此方法计算单元格高度
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard let audioTitle = audioData[indexPath.row].audioTitle else {return 50}
return estimatedHeightOfLabel(text: audioTitle, fontSize: 20, fontName: "AvenirNext-Medium", screenWidth: view.frame.width) + 16
}
但是,在我的自定义 tableView 单元类中,init 内的框架高度仍然是 44。
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .gray
backgroundColor = .clear
print(frame.height) //value is 44
}
因此,我必须使用layoutIfneeded 来更新我的框架高度,以便我可以将它用于我的标签高度 anchor 。
override func layoutIfNeeded() {
print(frame.height) // 56, 70, etc.
setupViews()
}
但是我里面的代码被调用了两次,比如 56,56,70,70 等。有什么想法吗?有办法避免吗?我也尝试过layoutSubviews,但里面的代码被调用了4次。 :)
最佳答案
在 iOS 11 上,使用 tableView.estimatedRowHeight = 0
禁用估计行高。
另外,重写layoutSubviews()
而不是layoutIfNeeded
。
override func layoutSubviews() {
super.layoutSubviews()
setupViews()
}
关于ios - layoutIfNeeded 内的代码被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48263855/