如何计算UitableView中的标头的正确高度



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

这是我要根据其内容计算正确高度时使用的。

        var fitSize = UIView.layoutFittingCompressedSize
        fitSize.width = superView.bounds.width
        let size = systemLayoutSizeFitting(fitSize,
                                           withHorizontalFittingPriority: UILayoutPriority.defaultHigh,
                                           verticalFittingPriority: UILayoutPriority.fittingSizeLevel)

最新更新