Animated resizing of UITableView header

No Comments

Other day i was working on a project in which we had a UITableViewController configured with a UITableView in which tableHeaderView property would be set to a custom UIView reference. The custom view is then used to display variable amount of information and it was required that it shrinks when the content in it becomes less. So, i tried a few things and it turned out that UITableView considers the header view for the layout calculations only once you set it. When you change a frame of the header view, the UITableView is not getting aware of this.

The solution to the described problem was then rather simple: just put the tableHeaderView property assignment operation inside of the animation block in which you would change the frame of the header view itself. Then Core Animation thread will set the property, every time, frame is adjusted. Something like that:

// Calculate new frame size for the table header
CGRect newRect = ...;
// Get the reference to the header view
UIView *tblHeaderView = self.tableView.tableHeaderView;
// Animate the height change
[UIView animateWithDuration:0.5 animations:^{
    tblHeaderView.frame = newRect;
    self.tableView.tableHeaderView = tblHeaderView;
}];

Typical scenario would be to put an Ad banner into the UITableView’s header and then animate it away when it becomes unavailable or so. The initial problem i had did cost some research, so i thought it would be worth sharing. Hope you’ll find it useful.

{facebook-share} Bookmark and Share

Leave a Reply

*