Forked from jashenson/JSTableWithFixedHeaderViewController.m
Created
July 23, 2016 03:51
-
-
Save jacks205/cdb309eaaa705c3a5dba943a7a5493eb to your computer and use it in GitHub Desktop.
Custom fixed UITableView header
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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