user172902
user172902

Reputation: 3601

Insert Custom Section Header Constraint Warning

When I am inserting an extra section to my project with a custom section header xib file, I get this problem where I get all sorts of constraint warning if the current view is at the very bottom of the screen. These warning does not appear if the view is not at the very bottom of the screen when the add button is pressed.

I do not get this problem when I choose to do reloadData instead of inserting a new cell. However, I do not want to re-load the whole table just to get a new cell.

I have uploaded a mini sample project that illustrates my problem. Below is how you could replicate the problem

  1. When the app launch you would be 3 sections with 2 rows for each section. With the view at Section 0, if you click the add button, an extra section would be added to the bottom of the table. And that would be section 3. No constraint warnings here

  2. Scroll all the way to the bottom until you reached the very bottom of the tableView where section 3 row 0 and section 3 row 1 is displayed. Now click the Add button and you will see all these constraint warnings which I was referring to.

Github Insert Section Header Sample Project

Upvotes: 1

Views: 611

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52183

When using Auto Layout for positioning views in your view hierarchy, you should avoid setting frame or some fixed dimensions as much as possible. The problem in your code is, you are giving a fixed height for header which is something Auto Layout doesn't like:

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  return 260.0
}   

You should change it to

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  return UITableViewAutomaticDimension
}

and inform UITableView about the estimated height:

tableView.estimatedSectionHeaderHeight = 260.0

so table view will infer the height based on the layout constraints and content in the header.

For more information please read self-sizing cells and headers section in the documentation.

Upvotes: 1

Related Questions