How to prevent tableview section head from sticking while scrolling?

Viewed 10990

I have a tableview with many sections. I am using an actual tableview cell which I dequeue to use as a custom section header. The issue I am having is when I scroll the section header "sticks" to the top of the table until the next section appears.

How can I prevent this from happening and actually have it scroll up like normal?

Here is my code

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if section == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "headerCell") as! HeaderTableViewCell
        return cell
    }
    return UIView()
}
6 Answers

Do following steps.

From @IB

  1. Select your tableView
  2. Go to Attribute Inspector
  3. Find Style Attribute drop down which is Plain by default
  4. Change it to Grouped

Or if you are creating TableView Programmatically use

let tableView = UITableView(frame: YourFrame, style: .Grouped)

Change UITableViewStyle to UITableViewStyleGrouped.

Set UITableViewStyle to UITableViewStyleGrouped, the headers will scroll up with the cells. and

func tableView(_ tableView: UITableView, 
heightForFooterInSection section: Int) -> CGFloat
{
    return 0.000001;
}

Step1: Go to Mainstoryboard

Step2: Click on Your Tableview

Step3: Go to Attribute Inspector

Step4: Find Style Attribute drop down which is Plain by default

Step5: Change it to Grouped

enter image description here

Some possible solutions :

  1. If you have just one section then set the Tableview Header property to the UIView you want to set as the Section Header.
  2. If you have multiple sections, change the row count for each section to (number of rows for that section + 1) and make the row at 0th index to be a header. Some hand coding will be required.
  3. Change your tableview to grouped, will require UI redesign so that the design looks similar to a plain tableview cell.

Instead of UIHeaderViewCell, You should use a UITableViewCell. Make section header height as 0 and for every 0th item in that section , display a UITableViewCell with heading on it

Related