头部放大是移动端开发常用到的UI,这里封装了一个便于使用的头部方放大工具,UITableView 和 UICollectionView 都可以使用
+ (VVScrollViewHelper *)initWithScrollView:(UIScrollView *)scrollView
headerViewConfig:(VVScrollExtraViewConfig *)headerConfig
{
VVScrollViewHelper *scrollViewHelper = [[self alloc] init];
if(scrollViewHelper){
headerConfig.frontView.clipsToBounds = YES;
headerConfig.backgroundView.clipsToBounds = YES;
scrollViewHelper.extraHeaderViewConfig = headerConfig;
CGRect frame = headerConfig.frontView.frame;
CGPoint origin = frame.origin;
///y原点 = 背景视图的原高度 - inset高度
origin.y = - (CGRectGetHeight(frame) - headerConfig.headerOverHeight);
frame.origin = origin;
headerConfig.frontView.frame = frame;
headerConfig.backgroundView.frame = frame;
scrollViewHelper.scrollView = scrollView;
scrollViewHelper.contentInsetTop = CGRectGetHeight(frame) - headerConfig.headerOverHeight;
scrollViewHelper.contentInsetBottom = 0;
scrollView.contentInset = UIEdgeInsetsMake(scrollViewHelper.contentInsetTop, 0, scrollViewHelper.contentInsetBottom, 0);
[scrollView setContentOffset:CGPointMake(0, -scrollViewHelper.contentInsetTop) animated:NO];
scrollView.bouncesZoom = NO;
[scrollView addSubview:headerConfig.backgroundView];
[scrollView addSubview:headerConfig.frontView];
scrollViewHelper.frontViewFrame = headerConfig.frontView.frame;
}
return scrollViewHelper;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (self.extraHeaderViewConfig) {
CGRect frame = self.extraHeaderViewConfig.frontView.frame;
CGPoint origin = frame.origin;
CGSize size = frame.size;
///下拉,
BOOL downPull = !(scrollView.contentOffset.y > - (CGRectGetHeight(frame) - self.extraHeaderViewConfig.headerOverHeight));
///放大
BOOL expand = self.extraHeaderViewConfig.headerStyle == VVHeaderBackStyleExpand;
if (downPull && expand) {
///初始偏移量为 (-self.contentInsetTop
origin.y = scrollView.contentOffset.y;
size.height = - scrollView.contentOffset.y + self.extraHeaderViewConfig.headerOverHeight;
frame.origin = origin;
frame.size = size;
self.extraHeaderViewConfig.backgroundView.frame = frame;
}
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
///将背景视图插到最底层
[scrollView insertSubview:self.extraHeaderViewConfig.backgroundView
atIndex:0];
///将顶部内容视图插到第二底层,防止覆盖cell,导致cell不能点击
[scrollView insertSubview:self.extraHeaderViewConfig.frontView atIndex:1];
});
}
- (VVScrollViewHelper *)headerHelper
{
if (!_headerHelper) {
VVScrollExtraViewConfig *config = [[VVScrollExtraViewConfig alloc] init];
config.backgroundView = self.imgView;
config.frontView = self.headerContentView;
config.headerOverHeight = 40;
_headerHelper = [VVScrollViewHelper initWithScrollView:self.tableView headerViewConfig:config];
}
return _headerHelper;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self.headerHelper scrollViewDidScroll:scrollView];
}
demo
如果对你有帮助,欢迎star