Tableview header is overlapping the cells

926 Views Asked by At

I have a view controller with a table view. Tableview has a table view header and dynamic cells. I have added a UIView as table view header and it has multiple labels with dynamic heights. All works fine.

But the problem occurs when the size of the view(used as table view header) get extended because of the extra height of labels(cause it gets extended due to extra contents) used in the view.

As a result, the upper cells of table view gets hidden or overlapped by the header view. Can anybody help me with this scenario? All these done using storyboards.

1

There are 1 best solutions below

0
On

You can't change table view header's height when you add it in the storyboard. Create the table view header programmatically and return UITableView.automaticDimension in heightForHeaderInSection method.

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.estimatedSectionHeaderHeight = 100
    tableView.sectionHeaderHeight = UITableView.automaticDimension
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = UIView()

    let lbl = UILabel()
    lbl.text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
    lbl.numberOfLines = 0
    lbl.lineBreakMode = .byWordWrapping
    lbl.translatesAutoresizingMaskIntoConstraints = false
    header.addSubview(lbl)

    header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(10)-[lbl(>=30)]-(10)-|", options: [], metrics: nil, views: ["lbl":lbl]))
    header.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(30)-[lbl]-(30)-|", options: [], metrics: nil, views: ["lbl":lbl]))
    return header
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableView.automaticDimension
}