Created
April 26, 2021 12:20
-
-
Save mattio/f3fb7dfb8e1ad7901bb663ba577a157b to your computer and use it in GitHub Desktop.
Variable-height UITableView tableHeaderView with autolayout
This file contains 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
// in a UITableViewController (or any other view controller with a UITableView) | |
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator | |
{ | |
UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, size.width, 0)]; | |
header.translatesAutoresizingMaskIntoConstraints = NO; | |
// [add subviews and their constraints to header] | |
NSLayoutConstraint *headerWidthConstraint = [NSLayoutConstraint | |
constraintWithItem:header attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual | |
toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0f constant:size.width | |
]; | |
[header addConstraint:headerWidthConstraint]; | |
CGFloat height = [header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; | |
[header removeConstraint:headerWidthConstraint]; | |
header.frame = CGRectMake(0, 0, size.width, height); | |
header.translatesAutoresizingMaskIntoConstraints = YES; | |
self.tableView.tableHeaderView = header; | |
} | |
- (void)viewWillAppear:(BOOL)animated | |
{ | |
[super viewWillAppear:animated]; | |
[self viewWillTransitionToSize:self.tableView.bounds.size withTransitionCoordinator:nil]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment