如何调整 UITableView 的 tableHeaderView 的大小?

我在调整表头视图的大小时遇到了麻烦,简单的方法不起作用。

1)创建 UITableView 和 UIView (100x320px) ;

2)将 UIView 设置为 UITableView 的 tableHeaderView;

3)构建和运行。一切都很好。

现在,我想调整 tableHeaderView 的大小,所以我在 viewDidLoad 中添加了以下代码:

self.tableView.autoresizesSubviews = YES;


self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;


CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;

TableHeaderView 的高度应该显示为200,但显示为100。

如果我写:

self.tableView.autoresizesSubviews = YES;




CGRect newFrame = myHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
myHeaderView.frame = newFrame;




self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;

然后从200米开始,如我所愿。但是我希望能够在运行时修改它。

我也尝试过这种方法,但没有成功:

self.tableView.autoresizesSubviews = YES;


self.tableView.tableHeaderView = myHeaderView;
self.tableView.tableFooterView = myFooterView;


CGRect newFrame = self.tableView.tableHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
self.tableView.tableHeaderView.frame = newFrame;


[self.tableView.tableHeaderView setNeedsLayout];
[self.tableView.tableHeaderView setNeedsDisplay];
[self.tableView setNeedsLayout];
[self.tableView setNeedsDisplay];

重点是: 如何在运行时调整 tableHeaderView 的大小? ? ?

有人能做到吗?

谢谢

94298 次浏览

Did you try [self.tableView reloadData] after changing the height?

I think it should work if you just set the height of myHeaderView like so:

CGRect newFrame = myHeaderView.frame;
newFrame.size.height = newFrame.size.height + 100;
myHeaderView.frame = newFrame;


self.tableView.tableHeaderView = myHeaderView;

FYI: I've gotten this to work by modifying the tableHeaderView and re-setting it. In this case, i'm adjusting the size of the tableHeaderView when the UIWebView subview has finished loading.

[webView sizeToFit];
CGRect newFrame = headerView.frame;
newFrame.size.height = newFrame.size.height + webView.frame.size.height;
headerView.frame = newFrame;
[self.tableView setTableHeaderView:headerView];

This answer is old and apparently doesn't work on iOS 7 and above.

I ran into the same problem, and I also wanted the changes to animate, so I made a subclass of UIView for my header view and added these methods:

- (void)adjustTableHeaderHeight:(NSUInteger)newHeight{
NSUInteger oldHeight = self.frame.size.height;
NSInteger originChange = oldHeight - newHeight;


[UIView beginAnimations:nil context:nil];


[UIView setAnimationDuration:1.0f];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];


self.frame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
self.frame.size.width,
newHeight);


for (UIView *view in [(UITableView *)self.superview subviews]) {
if ([view isKindOfClass:[self class]]) {
continue;
}
view.frame = CGRectMake(view.frame.origin.x,
view.frame.origin.y - originChange,
view.frame.size.width,
view.frame.size.height);
}


[UIView commitAnimations];
}


- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
[(UITableView *)self.superview setTableHeaderView:self];
}

This essentially animates all the subviews of the UITableView that aren't the same class type as the calling class. At the end of the animation, it calls setTableHeaderView on the superview (the UITableView) – without this the UITableView contents will jump back the next time the user scrolls. The only limitation I've found on this so far is if the user attempts to scroll the UITableView while the animation is taking place, the scrolling will animate as if the header view hasn't been resized (not a big deal if the animation is quick).

Its because the setter of tableHeaderView.

You have to set the UIView height before set the tableHeaderView. (Would be much easier if Apple open sources this framework...)

I found the initWithFrame initializer of a UIView doesn't properly honor the rect I pass in. Hence, I did the following which worked perfectly:

 - (id)initWithFrame:(CGRect)aRect {


CGRect frame = [[UIScreen mainScreen] applicationFrame];


if ((self = [super initWithFrame:CGRectZero])) {


// Ugly initialization behavior - initWithFrame will not properly honor the frame we pass
self.frame = CGRectMake(0, 0, frame.size.width, 200);


// ...
}
}

The advantage of this is it is better encapsulated into your view code.

If you want to conditionally animate the changes you can do the following:

- (void) showHeader:(BOOL)show animated:(BOOL)animated{


CGRect closedFrame = CGRectMake(0, 0, self.view.frame.size.width, 0);
CGRect newFrame = show?self.initialFrame:closedFrame;


if(animated){
// The UIView animation block handles the animation of our header view
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.3];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];


// beginUpdates and endUpdates trigger the animation of our cells
[self.tableView beginUpdates];
}


self.headerView.frame = newFrame;
[self.tableView setTableHeaderView:self.headerView];


if(animated){
[self.tableView endUpdates];
[UIView commitAnimations];
}
}

Please note that the animation is two-folded:

  1. The animation of the cells below the tableHeaderView. This is done using beginUpdates and endUpdates
  2. The animation of the actual header view. This is done using a UIView animation block.

In order to synchronize those two animations the animationCurve has to be set to UIViewAnimationCurveEaseInOut and the duration to 0.3, which seems to be what the UITableView uses for it's animation.

Update

I created an Xcode project on gihub, which does this. Check out the project ResizeTableHeaderViewAnimated in besi/ios-quickies

screenshot

Used @garrettmoon solution above until iOS 7.
Here's an updated solution based on @garrettmoon's:

- (void)adjustTableHeaderHeight:(NSUInteger)newHeight animated:(BOOL)animated {


[UIView beginAnimations:nil context:nil];


[UIView setAnimationDuration:[CATransaction animationDuration]];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];


self.frame = CGRectMake(self.frame.origin.x,
self.frame.origin.y,
self.frame.size.width,
newHeight);


[(UITableView *)self.superview setTableHeaderView:self];


[UIView commitAnimations];
}


- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
[(UITableView *)self.superview setTableHeaderView:self];
}

I have implemented animated height change of the table's header to expand to overall screen when tapped. However, the code can help in other cases:

// Swift
@IBAction func tapped(sender: UITapGestureRecognizer) {


self.tableView.beginUpdates()       // Required to update cells.


// Collapse table header to original height
if isHeaderExpandedToFullScreen {


UIView.animateWithDuration(0.5, animations: { () -> Void in
self.scrollView.frame.size.height = 110   // original height in my case is 110
})


}
// Expand table header to overall screen
else {
let screenSize = self.view.frame           // "screen" size


UIView.animateWithDuration(0.5, animations: { () -> Void in
self.scrollView.frame.size.height = screenSize.height
})
}


self.tableView.endUpdates()  // Required to update cells.


isHeaderExpandedToFullScreen= !isHeaderExpandedToFullScreen  // Toggle
}

This worked for me on iOS 7 and 8. This code is running on the table view controller.

[UIView animateWithDuration:0.3 animations:^{
CGRect oldFrame = self.headerView.frame;
self.headerView.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.size.width, newHeight);
[self.tableView setTableHeaderView:self.headerView];
}];

UITableView resizing header - UISearchBar with Scope Bar

I wanted a UITableView with a UISearchBar as the header to the table so I have a hierarchy that looks like this

UITableView
|
|--> UIView
|     |--> UISearchBar
|
|--> UITableViewCells

UISearchBarDelegate methods

As has been stated elsewhere, if you don't setTableViewHeader after changing it, nothing will happen.

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsScopeBar = YES;
[UIView animateWithDuration:0.2f animations:^{
[searchBar sizeToFit];
CGFloat height = CGRectGetHeight(searchBar.frame);


CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = height;
self.tableHeaderView.frame = frame;
self.tableView.tableHeaderView = self.tableHeaderView;
}];


[searchBar setShowsCancelButton:YES animated:YES];
return YES;
}


- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
searchBar.showsScopeBar = NO;
[UIView animateWithDuration:0.f animations:^{
[searchBar sizeToFit];


CGFloat height = CGRectGetHeight(searchBar.frame);


CGRect frame = self.tableView.tableHeaderView.frame;
frame.size.height = height;
self.tableHeaderView.frame = frame;
self.tableView.tableHeaderView = self.tableHeaderView;
}];


[searchBar setShowsCancelButton:NO animated:YES];
return YES;
}

If custom headerView is designed using autolayout and headerView needs to be updated after web-fetch or similar lazy task. then in iOS-Swift I did this and got my headerView updated using bellow code:

//to reload your cell data
self.tableView.reloadData()
DispatchQueue.main.async {
// this is needed to update a specific tableview's headerview layout on main queue otherwise it's won't update perfectly cause reloaddata() is called
self.tableView.beginUpdates()
self.tableView.endUpdates()
}

On iOS 9.x, doing this on viewDidLoad works just fine:

var frame = headerView.frame
frame.size.height = 11  // New size
headerView.frame = frame

headerView is declared as @IBOutlet var headerView: UIView! and connected on the storyboard, where it is placed at the top of the tableView, to function as the tableHeaderView.

Setting the height for header view property tableView.tableHeaderView in viewDidLoad seems not work, the header view height still not change as expected.

After fighting against this issue for many tries. I found that, you can change the height by invoking the header view create logic inside the - (void)didMoveToParentViewController:(UIViewController *)parent method.

So the example code would look like this:

- (void)didMoveToParentViewController:(UIViewController *)parent {
[super didMoveToParentViewController:parent];


if ( _tableView.tableHeaderView == nil ) {
UIView *header = [[[UINib nibWithNibName:@"your header view" bundle:nil] instantiateWithOwner:self options:nil] firstObject];


header.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), HeaderViewHeight);


[_tableView setTableHeaderView:header];
}
}

On iOS 9 and below, tableHeaderView would not re-layout after resizing it. This issue is resolved in iOS 10.

To solve this issue, just do it with the following code:

self.tableView.tableHeaderView = self.tableView.tableHeaderView;

Obviously, by now Apple should have implemented UITableViewAutomaticDimension for tableHeaderView & tableFooterView...

The following seems to work for me using layout contraint(s):

CGSize   s  = [ self  systemLayoutSizeFittingSize : UILayoutFittingCompressedSize ];
CGRect   f  = [ self  frame ];


f.size   = s;


[ self  setFrame : f ];

If your tableHeaderView is a content adjustable webView,you can try:

[self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
self.webView.height = self.webView.scrollView.contentSize.height;
self.tableView.tableHeaderView = self.webView;
}

I tested it on iOS9 and iOS11,worked well.

This is only for when you use auto-layout and set translatesAutoresizingMaskIntoConstraints = false to a custom header view.

The best and the simplest way is to override intrinsicContentSize. Internally UITableView uses intrinsicContentSize to decide its header/footer size. Once you have override intrinsicContentSize in your custom view, What you need to do is as below

  1. configure the custom header/footer view's layout(subviews)
  2. invoke invalidateIntrinsicContentSize()
  3. invoke tableView.setNeedsLayout() and tableView.layoutIfNeeded()

Then the UITableView's header/footer will be updated as you want. No need to set the view nil or reset.

One thing really interesting for the UITableView.tableHeaderView or .tableFooterView is that UIStackView loose its ability to manage its arrangedSubviews. If you want to use UIStackView as a tableHeaderView or tableFooterView, you have to embed the stackView in a UIView and override UIView's intrinsicContentSize.

For swift 5 Tested code

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()


guard let headerView = self.tblProfile.tableHeaderView else {
return
}


let size = headerView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)


if headerView.frame.size.height != size.height {
headerView.frame.size.height = size.height
self.tblProfile.tableHeaderView = headerView
self.tblProfile.layoutIfNeeded()
}
}

Note : You need to give all subview's constraints form top, bottom, leading, trailing. So it will get whole required size.

Reference taken from : https://useyourloaf.com/blog/variable-height-table-view-header/