0

I have a 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. 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
rahul
  • 1
  • 2

1 Answers1

0

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)
Aura
  • 246
  • 1
  • 10