How to resize a tableHeaderView of a UITableView?

后端 未结 19 2218
死守一世寂寞
死守一世寂寞 2020-11-29 16:14

I\'m having trouble resizing a tableHeaderView. It simple doesn\'t work.

1) Create a UITableView and UIView (100 x 320 px);

2) Set the UIView as tableHeaderV

19条回答
  •  一生所求
    2020-11-29 17:06

    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).

提交回复
热议问题