Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inset Grouped UITableView with Header Section

I have Used UITableView with Two prototype Cells and Inset Grouped style

enter image description here

Without viewForHeaderInSection Output will be fine

enter image description here

After Add viewForHeaderInSection Output will be Like this

enter image description here

Expected Output

enter image description here

Here is my code

extension DashboardVC:UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 45
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headerCell = tableView.dequeueReusableCell(withIdentifier: "TblHeaderCell") as! TblHeaderCell
        return headerCell
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TblSectionCell", for: indexPath) as! TblSectionCell
        return cell
    }
}
like image 211
Nikunj Kumbhani Avatar asked Sep 10 '25 03:09

Nikunj Kumbhani


1 Answers

First, Inset Grouped tableView's have additional alignment properties...

If you use default cells and simply set the titleForHeaderInSection, you'll see that the text in the section header is aligned with the text in the cell.

In addition, Inset Grouped rounds the corners of the section of rows -- it does NOT include the section header.

Here's how it looks with a plain UIView as the section header view:

enter image description here

Zoomed in a little:

enter image description here

To get the visual output you're going for, I think you'll want to use your "header cell" as the first row in the section, and your "section cell" for the remaining rows:

enter image description here

I'm guessing the "down arrow / chevron" in your section header indicates you want to expand / collapse the sections? If so, you'll need to refactor your code to display only the first row when the section is collapsed.

Another option would be to NOT use Inset Grouped, and instead customize your cells to round the top corners of the section header and bottom corners of only the last cell in the section ... or round all 4 corners of the header when the section is collapsed.

like image 140
DonMag Avatar answered Sep 12 '25 19:09

DonMag