0

I need help getting rid of the space between my TableView's main header and a section header.

   let tableView: UITableView = {
       let tableView = UITableView(frame: .zero, style: .plain)
       return tableView
   }()

   tableView.tableHeaderView = postView

The post view is dynamic so I cannot set the height for that headerView in the delegate method.

I want the postView and the section below it together, but there is the weird space.

enter image description here

2 Answers2

0

Try this code Setting tableHeaderView height dynamically

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    if let headerView = tableView.tableHeaderView {

        let height = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
        var headerFrame = headerView.frame

        //Comparison necessary to avoid infinite loop
        if height != headerFrame.size.height {
            headerFrame.size.height = height
            headerView.frame = headerFrame
            tableView.tableHeaderView = headerView
        }
    }
}
SEUNGHWAN LEE
  • 204
  • 1
  • 4
0

Try the following:

let tableView: UITableView = {
    let tableView = UITableView(frame: .zero, style: .grouped)
    return tableView
}()

tableView.tableHeaderView = postView
  • Be aware that using a grouped style will also cause the headers to lock to the top cell for each section, rather than allowing the section cells to scroll independently. – SimonMoss Nov 17 '21 at 15:44
  • Thanks, I know grouped style always sticks the section header with the cell. If it's not an issue this will work. – Shamseer Ali Nov 18 '21 at 08:26