4

I have a tableview with a tableview header (not section header) that both resize depending on the orientation. In my implementation I'm setting the frames for both views in viewWillLayoutSubviews.

My problem right now is that while both are resizing properly individually after rotating, the tableView's origin isn't changing to take into account of the header's height change. This is leading to a space appearing between them or the header covering some of the cells.

My goal is to have in portrait, the tableview be of screen width with a long header. When rotated to landscape the width diminishes to a third of the screen width, right justified, with a shorter header. As well, I need the rotation animation for all of these changes to be smooth and logical.

I'm fairly green to iOS rotation and animation practises so if anyone has better suggestions I'd definitely appreciate them.

K.He
  • 137
  • 1
  • 8

2 Answers2

1

Table view won't respect new header height until you reassign tableHeader.

Similar questions:

When rotation will or did finish you could do the following:

- (void)didRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    self.tableView.tableHeaderView = self.tableView.tableHeaderView;
}

In fact, here's also the place where you could calculate header's height:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    CGRect frame = self.tableView.tableHeaderView.frame;
    frame.size.height = UIInterfaceOrientationIsLandscape(toInterfaceOrientation) ? 50 : 150;
    self.tableView.tableHeaderView.frame = frame;

    self.tableView.tableHeaderView = self.tableView.tableHeaderView;
}
Community
  • 1
  • 1
vokilam
  • 10,153
  • 3
  • 45
  • 56
  • 1
    Hi, reassigning the header was what I was missing. After setting the frame of the header, I called setTableHeaderView with self.tableView.tableHeaderView. Now everything looks great. Thanks a lot. – K.He Feb 13 '14 at 20:04
  • 1
    The method signature in the first code example should be `-didRotateFromInterfaceOrientation:` instead of `-didRotateToInterfaceOrientation:duration:`. – Frederik May 06 '14 at 17:59
1

On iOS 8.0+ you can call instead:

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator;

If you override the method, make sure you call super at some point.

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {

    coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) in



        self.tableView.tableHeaderView? = YourTableHeaderView()

    }, completion: { (UIViewControllerTransitionCoordinatorContext) in



    })

    super.viewWillTransition(to: size, with: coordinator)
}
sheinix
  • 167
  • 1
  • 13