制作一个顶部图片可以拉伸放大缩小效果的tableViewHeader

  最近负责公司项目个人中心的项目模块研发,首页是一个头部图片可以拉伸放大缩小效果的tableViewHeader,今天这个demo和教程我增加了模糊效果和头像缩小效果。具体效果如图:

制作一个顶部图片可以拉伸放大缩小效果的tableViewHeader_第1张图片

  如果这个效果是想要学习的可以去这里下载我的demo:http://pan.baidu.com/s/1qXeFR0g

  开发这类效果的TableViewHeader一般是通过监听scrollViewDidScroll:代理方法知道contenOffset值的变化,从而通过这个值的变化调整头部背景图的大小或者其他图片的大小(如本例子的头像视图)。

  重点代码如下:

- (void)updateSubViewsWithScrollOffset:(CGPoint)newOffset {
    CGFloat destinaOffset = -64;
    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-40; // 子视图的偏移量
    CGFloat newY = -newOffset.y-self.scrollView.contentInset.top;
    CGFloat d = destinaOffset-startChangeOffset;
    CGFloat alpha = 1-(newOffset.y-startChangeOffset)/d;
    CGFloat imageReduce = 1-(newOffset.y-startChangeOffset)/(d*2);
    self.subTitleLabel.alpha = alpha;
    self.titleLabel.alpha = alpha;
    self.frame = CGRectMake(0, newY, self.frame.size.width, self.frame.size.height);
    self.backImageView.frame = CGRectMake(0, -0.5*self.frame.size.height+(1.5*self.frame.size.height-64)*(1-alpha), self.backImageView.frame.size.width, self.backImageView.frame.size.height);
    
    CGAffineTransform t = CGAffineTransformMakeTranslation(0,(subviewOffset-0.35*self.frame.size.height)*(1-alpha));
    _headerImageView.transform = CGAffineTransformScale(t,
                                                        imageReduce, imageReduce);
    
    self.titleLabel.frame = CGRectMake(0, 0.6*self.frame.size.height+(subviewOffset-0.45*self.frame.size.height)*(1-alpha), self.frame.size.width, self.frame.size.height*0.2);
    self.subTitleLabel.frame = CGRectMake(0, 0.75*self.frame.size.height+(subviewOffset-0.45*self.frame.size.height)*(1-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, 0, 0, 0);
    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];
    }
}

  

你可能感兴趣的:(制作一个顶部图片可以拉伸放大缩小效果的tableViewHeader)