Created
April 9, 2020 17:21
-
-
Save AlexNachbaur/a96dfd5f2923cd67391ad58f909b6deb to your computer and use it in GitHub Desktop.
Height-adjusting table 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
@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