首先上效果图
改自这个库的代码,主要是为了实现上图中tableHeaderView的视差效果
关键代码如下:
- (void)initialSetupForCustomSubView:(UIView *)subView { //初始化中间层imageScrollView UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds]; self.imageScrollView = scrollView; //设置内容层的自动布局并存储 subView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; self.subView = subView; //将内容层View添加到scrollView上 [self.imageScrollView addSubview:subView]; [self addSubview:self.imageScrollView]; } - (void)layoutHeaderViewForScrollViewOffset:(CGPoint)offset { CGRect frame = self.imageScrollView.frame; if (offset.y > 0) { frame.origin.y = MAX(offset.y *kParallaxDeltaFactor, 0); self.imageScrollView.frame = frame; self.clipsToBounds = YES; } else { CGFloat delta = 0.0f; CGRect rect = kDefaultHeaderFrame; delta = fabs(MIN(0.0f, offset.y)); rect.origin.y -= delta; rect.size.height += delta; self.imageScrollView.frame = rect; self.clipsToBounds = NO; } }
override func scrollViewDidScroll(scrollView: UIScrollView) { let header: ParallaxHeaderView = self.tableView.tableHeaderView as! ParallaxHeaderView header.layoutHeaderViewForScrollViewOffset(scrollView.contentOffset) }