我正在尝试根据内容制作具有动态单元格高度的 UITableView。我的应用程序是一个文章查看器。我尝试用这些函数计算单元格的高度。
func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
label.numberOfLines = 0
label.lineBreakMode = .ByTruncatingTail
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let post = FeedController.sharedController.allPosts[indexPath.row]
var height = 16.0
if post.hasImage {
height += Double(self.view.frame.width) / (4/3)
}
let titleH = heightForView(post.title!, font: UIFont(name: "LiberationSerif-Bold", size: 20.0)!, width: self.tableView.bounds.width)
let descH = heightForView(post.desc!, font: UIFont(name: "LiberationSerif", size: 17.0)!, width: self.tableView.bounds.width)
let totalHeight = CGFloat(height+Double(titleH)+Double(descH))
print("imageH: \(height), titleH: \(titleH) detailH: \(descH) totalH:\(totalHeight)")
return totalHeight
}
当我运行它时,它看起来像这样,如您所见,底部标签被切断。
![enter image description here](https://i.stack.imgur.com/yYQha.png)
我通过接口断点运行了它,在这里你可以看到错误的原因:
![enter image description here](https://i.stack.imgur.com/HWcjp.png)
渲染的尺寸比 sizeToFit() 估计的尺寸大一号,正如您从我的日志语句中看到的那样:
imageH: 297.25, titleH: 44.5 detailH: 56.5 totalH:398.25
我怀疑这个计算错误的原因是我为 heightForView 函数提供了错误的宽度参数。我尝试过使用 tableView.contentSize 和许多其他东西。 lineBreakMode 在我的故事板和代码中是相同的。
我想我需要的是一种更好的方法来找到单元格的预期宽度,或者任何其他可以给我正确的预期高度的解决方案。
Edit: Constraints:
![enter image description here](https://i.stack.imgur.com/o2APy.png)