user7097242
user7097242

Reputation: 1074

How to prevent tableview section head from sticking while scrolling?

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()
}

Upvotes: 13

Views: 15843

Answers (7)

Anees
Anees

Reputation: 522

If you have created your TableView programmatically you can make it grouped in the initialser itself. So the section header won't be sticky.

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

Upvotes: 0

Ajay saini
Ajay saini

Reputation: 2470

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)

Upvotes: 28

khushbu arthania
khushbu arthania

Reputation: 29

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

Upvotes: 2

Fahad Azeem
Fahad Azeem

Reputation: 651

Change UITableViewStyle to UITableViewStyleGrouped.

Upvotes: 4

Syed Sadrul Ullah Sahad
Syed Sadrul Ullah Sahad

Reputation: 1312

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

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

Upvotes: 3

ahmed
ahmed

Reputation: 568

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

Upvotes: 0

B K
B K

Reputation: 1564

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.

Upvotes: 2

Related Questions