ios - layoutIfNeeded 内的代码被调用两次

标签 ios swift uitableview

我有一个表格 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/

相关文章:

iOS运行时内存限制

ios - 在 Objective C 中使用 static init 有什么好处?

ios - 调用 In App Purchase 时出错 - swift

ios - TableView 滚动错误

ios 应用程序仅在 ios 9 上使用图像文字填充单元格时崩溃,不清楚崩溃日志

iphone - 如何在 UIWebView 中打开我的 documentDirectory(来 self 的 UITableView)文件?

ios - DidSelect 突出显示更改 View 颜色不起作用

android - QuickBlox:发送消息不会在具有相同登录名的其他设备上更新

ios - 我想从标签中获取时间 09.30,因为 hr = 09 和 min = 30,可能吗?

ios - 框架和类共享名称的命名冲突