Skip to content

Instantly share code, notes, and snippets.

@NachoMan
Created April 9, 2020 17:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NachoMan/a96dfd5f2923cd67391ad58f909b6deb to your computer and use it in GitHub Desktop.
Save NachoMan/a96dfd5f2923cd67391ad58f909b6deb to your computer and use it in GitHub Desktop.
Height-adjusting table header.
@interface HeaderView : UIView
@end
@implementation HeaderView
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = UIColor.blueColor;
}
return self;
}
@end
@interface ViewController () <UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) HeaderView *headerView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
self.tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight);
[self.view addSubview:self.tableView];
self.tableView.dataSource = self;
self.tableView.delegate = self;
[self.tableView registerClass:UITableViewCell.class forCellReuseIdentifier:@"Cell"];
self.tableView.backgroundView = UIView.new;
self.headerView = HeaderView.new;
self.headerView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
self.headerView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 250);
[self.tableView.backgroundView addSubview:self.headerView];
self.tableView.contentInset = UIEdgeInsetsMake(CGRectGetHeight(self.headerView.bounds), 0, 0, 0);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
cell.textLabel.text = [NSString stringWithFormat:@"Cell %ld", indexPath.row];
return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
static CGFloat const HeaderMinimumHeight = 44.0;
CGFloat referenceHeight = self.tableView.contentInset.top;
CGFloat offset = referenceHeight + scrollView.contentOffset.y;
CGRect headerFrame = self.headerView.frame;
headerFrame.size.height = MAX(HeaderMinimumHeight, referenceHeight - offset);
self.headerView.frame = headerFrame;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment