[英]How to calculate right height of header in UITableView
I have a TableView. 我有一个TableView。 I added a header.
我添加了标题。 Header contains dynamically data.
标头包含动态数据。 So header height is calculating dynamically.
因此标题高度是动态计算的。 But sometime height is correct, sometime header having too much extra space and sometime header is overlapping with tableview.
但有时高度是正确的,有时候标题有太多的额外空间,有时候标题与tableview重叠。 Kindly have a look.
请看看。
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 0 {
//return totalHeaderHeight + 20
return UITableViewAutomaticDimension
} else {
return 0
}
}
func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return totalHeaderHeight
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView:UIView = UIView()
{
headerView.backgroundColor = .white
let label = CustomLabel(frame: CGRect(x: 10, y: 5, width: self.w - 10, height: 21))
label.text = self.listSpeakerData.name
label.font = UIFont(name: "robotocondensed-bold", size: 13)
label.textColor = .black
label.numberOfLines = 1
let label2 = CustomLabel(frame: CGRect(x: 10, y: label.frame.origin.y + label.frame.height + 5, width: self.w - 10, height: 21))
label2.text = "\n" + self.hrdData
// label2.text = "self.hrdData"
label2.font = UIFont(name: "roboto-regular", size: 13)
label2.textColor = .black
label2.numberOfLines = 0
label2.sizeToFit()
//draw a line.
let sepFrame1 = CGRect(x:0, y: label.frame.origin.y + label.frame.height + label2.frame.origin.y + label2.frame.height,
width: self.w, height: 0.5)
let seperatorView = UIView(frame: sepFrame1);
seperatorView.backgroundColor = UIColor.lightGray
headerView.addSubview(label)
headerView.addSubview(label2)
headerView.addSubview(seperatorView);
}
return headerView
} else {
return nil
}
}
This is my calculation code. 这是我的计算代码。
self.totalHeaderHeight = self.hrdData.height(withConstrainedWidth: self.w, font: UIFont(name: "roboto-regular", size: 14.5)!)
+ self.listSpeakerData.name.height(withConstrainedWidth: self.w, font: UIFont(name: "robotocondensed-bold", size: 14.5)!)
self.totalHeaderHeight = self.totalHeaderHeight + 10
This is what I use when I want to calculate the correct height of a view based on its content. 这是我想要根据内容计算视图的正确高度时使用的内容。
var fitSize = UIView.layoutFittingCompressedSize
fitSize.width = superView.bounds.width
let size = systemLayoutSizeFitting(fitSize,
withHorizontalFittingPriority: UILayoutPriority.defaultHigh,
verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.