最近负责公司项目个人中心的项目模块研发,首页是一个头部图片可以拉伸放大缩小效果的tableViewHeader,今天这个demo和教程我增加了模糊效果和头像缩小效果。具体效果如图:
如果这个效果是想要学习的可以去这里下载我的demo:http://pan.baidu.com/s/1qXeFR0g
开发这类效果的TableViewHeader一般是通过监听scrollViewDidScroll:代理方法知道contenOffset值的变化,从而通过这个值的变化调整头部背景图的大小或者其他图片的大小(如本例子的头像视图)。
重点代码如下:
- (void)updateSubViewsWithScrollOffset:(CGPoint)newOffset { CGFloat destinaOffset = -; CGFloat startChangeOffset = -self.scrollView.contentInset.top; newOffset = CGPointMake(newOffset.x, newOffset.y < startChangeOffset ? startChangeOffset : (newOffset.y > destinaOffset ? destinaOffset : newOffset.y)); CGFloat subviewOffset = self.frame.size.height-; // 子视图的偏移量 CGFloat newY = -newOffset.y-self.scrollView.contentInset.top; CGFloat d = destinaOffset-startChangeOffset; CGFloat alpha = -(newOffset.y-startChangeOffset)/d; CGFloat imageReduce = -(newOffset.y-startChangeOffset)/(d*); self.subTitleLabel.alpha = alpha; self.titleLabel.alpha = alpha; self.frame = CGRectMake(, newY, self.frame.size.width, self.frame.size.height); self.backImageView.frame = CGRectMake(, -)*(-alpha), self.backImageView.frame.size.width, self.backImageView.frame.size.height); CGAffineTransform t = CGAffineTransformMakeTranslation(,(subviewOffset--alpha)); _headerImageView.transform = CGAffineTransformScale(t, imageReduce, imageReduce); self.titleLabel.frame = CGRectMake(, -alpha), self.frame.size.width, self.frame.size.height*0.2); self.subTitleLabel.frame = CGRectMake(, -alpha), self.frame.size.width, self.frame.size.height*0.1); }
在我这个demo中我没有通过代理方法scrollViewDidScroll:获取contenOffset的值,而是用kvo观察contenOffset值的变化然后调用上面这个方法达到效果,效果和通过scrollViewDidScroll:代理方法是一样的。
- (void)willMoveToSuperview:(UIView *)newSuperview { [self.scrollView addObserver:self forKeyPath:@"contentOffset" options:(NSKeyValueObservingOptionNew) context:Nil]; self.scrollView.contentInset = UIEdgeInsetsMake(self.frame.size.height, , , ); self.scrollView.scrollIndicatorInsets = self.scrollView.contentInset;//滚动条的位置 } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { if ([keyPath isEqualToString:@"contentOffset"]) { CGPoint newOffset = [change[@"new"] CGPointValue]; [self updateSubViewsWithScrollOffset:newOffset]; } }