iosobjective-cuitableviewautolayouttableheader

Calculate tableHeaderView height with autolayout


This is my xib File:

enter image description here

As you can see i have a UITableView with a tableHeaderView (orange Color)! Everything is shown correct during runtime, except when the title Label have more than one Line, than the UILabel get´s cut off with the typically "..". I already changed the numberOfLines to 0!

I recognized the Problem is the Height of the whole tableHeaderView! This is how i calculated the Height in Code:

[self.headerView setNeedsLayout];
[self.headerView layoutIfNeeded];

CGFloat height = [self.headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height + self.headerView.frame.origin.y;

CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = height;
self.headerView.frame = headerFrame;

[self.tableView setTableHeaderView:self.headerView];

But during runtime the tableHeaderView is too small to show 2 or 3 or 4... Lines of the title Label. What could be the Problem?


Solution

  • I think you are trying too hard to fit you content into the tableview header, which was designed to contain relatively small static content.

    Assuming what you want is your tableview to stay at the bottom of the orange view, and the orange view to scroll with the tableview (ie. not stay at the top of the screen at all time), I would add a scroll view parent of both the orange view and the tableview, and disable the tableview scroll capability.

    This means however to exchange your UITableViewController for a UIViewController.

    eg.

    -- UIScrollView
      |
      -- UIView (orange view)
      | |
      | -- subview 1
      | -- subview 2
      | -- etc.
      |
      -- UITableView (scrollEnabled = NO)
    

    With AutoLayout, you can make the orange view resize automatically to fit its content, which will "push" the UITableView down. When the user swipe vertically, the root scrollview will catch the events, and scroll the whole (orangeView + tableView) accordingly, resulting in the same effect as if the orange view was the table view header.