我有一个TableView。我添加了标题。标头包含动态数据。因此标题高度是动态计算的。但是有时高度是正确的,有时标头具有过多的额外空间,并且有时标头与tableview重叠。请看看。
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
}
}
这是我的计算代码。
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
答案 0 :(得分:0)
这是我要根据其内容计算视图的正确高度时使用的方法。
var fitSize = UIView.layoutFittingCompressedSize
fitSize.width = superView.bounds.width
let size = systemLayoutSizeFitting(fitSize,
withHorizontalFittingPriority: UILayoutPriority.defaultHigh,
verticalFittingPriority: UILayoutPriority.fittingSizeLevel)