Search code examples
iosuitableviewcontentoffset

TableView ContentInset and ContentOffset


I trying to create a stretchy table view header and I saw this code on a post online:

override func viewDidLoad() {
    tableView.contentInset = UIEdgeInsets(top: kTableHeaderHeight, left: 0, bottom: 0, right: 0)
    tableView.contentOffset = CGPoint(x: 0, , y: -kTableHeaderHeight)
    updateHeaderView()
}

I am having a little trouble understanding this code.

So essentially what it is doing is (Assuming the screen is 0 to 500 in height and kTableHeaderHeight = 200):

1) It is first adding padding to the top of the tableView by moving it up by kTableHeaderHeight in the contentInset property (this move is with respect to the frame of the tableView). So now does the tableView exists from -200 to 500?

2) Then it moves its bounds up by -kTableHeaderHeight. So does the contentOffset just make it scrollable in the -200 to 500 region? So is that why we are using contentOffset by -kTableHeaderHeight in this case?


Solution

  • 1) No, if inset is positive then it makes table view area smaller, like 200,500

    2) contentOffset is state of tableview. so when you set offset to -200 it moves content zero point to 200 from table view zero point, regardless content inset. basically it put current table view content to place where it should be regarding inset

    So what that code does is reserves 200point place for custom header, that never overlaps with table view cells content (as table view API headers or footers do)