Skip to content

Instantly share code, notes, and snippets.

@jashenson
Created November 27, 2013 23:39
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jashenson/7684971 to your computer and use it in GitHub Desktop.
Save jashenson/7684971 to your computer and use it in GitHub Desktop.
Custom fixed UITableView header
// Key sections of code for this implementation are placed below
@interface JSTableWithFixedHeaderViewController ()
@property (strong, nonatomic) UIView *fixedHeaderView;
@end
@implementation JSTableWithFixedHeaderViewController
// The following code will insert our custom fixed header view in the appropriate hierarchy
- (void) viewWillAppear:(BOOL)animated
{
CGSize intrinsicSize = self.fixedHeaderView.intrinsicContentSize;
CGHeight height = (intrinsicSize.height > 0) ? intrinsicSize.height : 30; // replace with some fixed value as needed
CGFloat width = CGRectGetWidth(self.view.bounds);
CGRect frame = CGRectMake(0, 0, width, height);
self.fixedHeaderView.frame = frame;
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(height, 0, 0, 0);
UIView *wrapperView = self.tableView.subviews[0]; // this is a bit of a hack solution, but should always pull out the UITableViewWrapperView
[self.tableView insertSubview:self.fixedHeaderView aboveSubview:wrapperView];
}
- (void) scrollViewDidScroll:(UIScrollView *)scrollView
{
// Adjust the header's frame to keep it pinned to the top of the scroll view
CGRect headerFrame = self.fixedHeaderView.frame;
CGFloat yOffset = scrollView.contentOffset.y;
headerFrame.origin.y = MAX(0, yOffset);
self.fixedHeaderView.frame = headerFrame;
// If the user is pulling down on the top of the scroll view, adjust the scroll indicator appropriately
CGFloat height = CGRectGetHeight(headerFrame);
if (yOffset< 0) {
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(ABS(yOffset) + height, 0, 0, 0);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment