顶部视图下拉放大

iz32v-4pkiy.gif

往下滑动时图片放大,向上时图片随tableView滚出屏幕外。

实现过程

1.添加一个tableView

- (void)setupViews {
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc] init];
    _tableView.frame = self.view.bounds;
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
   
}

2.将tableView的headerView设为只包含一张图片的视图

 _tableView.tableHeaderView = self.tableHeaderView;
- (UIView *)tableHeaderView {
    if (!_tableHeaderView) {
        _tableHeaderView = [[HeaderBannerView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, headerHeight) image:[UIImage imageNamed:@"tableViewHeader"]];
    }
    return _tableHeaderView;
}
@interface HeaderBannerView : UIView

@property (nonatomic, strong) UIImageView *bannerImageView;
@end

@implementation HeaderBannerView

- (instancetype)initWithFrame:(CGRect)frame image:(UIImage *)image{
    if (self = [super initWithFrame:frame]) {
        self.bannerImageView = [[UIImageView alloc] initWithFrame:frame];
        self.bannerImageView.image = image;
        [self addSubview:self.bannerImageView];
    }
    return self;
}

3.在tableView滚动的时候设置图片imageView的frame

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    [self.tableHeaderView updateBannerImageViewFrameWithOffsetY:contentOffsetY];
}
- (void)updateBannerImageViewFrameWithOffsetY:(CGFloat)offsetY {
    if (offsetY <= 0) {
        offsetY = fabs(offsetY);
        CGFloat rate = offsetY / headerHeight;
        CGFloat diffX = rate * ScreenWidth;
        [self.bannerImageView setFrame:CGRectMake(-diffX/2, -offsetY, ScreenWidth+diffX, headerHeight+offsetY)];
    }
}

你可能感兴趣的:(顶部视图下拉放大)