iOS 图片下拉变大

前言

在iOS的开发中TableView和ScrollView是可以上下滑动的,但是在下拉的过程中,顶部会出现留白的现象,于是就出现了类似于QQ空间中那样下拉顶部的图片变大的效果。看起看很高大上,其实实现起来很简单。先看下效果图:

这里写图片描述

实现思路

实现这一效果我们需要用到ScrollView的ContentInset属性,contentInset 是scrollview中contentView.frame.origin与scrollview.frame.origin的关系。把ScrollView的contentView向下偏移200,留出一段空白的位置,在这段空白的位置上放上一张图片。然后在scrollView滚动的方法中,重现去设置图片的frame,下拉了多少就把image的高度放大多少。

scrollView的contentView默认的top是0,当往上滑动top的值正向变大,往下滑时top的值负向变大。

一、列表中实现图片下拉变大

关键代码:


#define IMAGE_HEIGHT    200

- (void)viewDidLoad {
    [super viewDidLoad];

    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];

    _tableView.contentInset = UIEdgeInsetsMake(IMAGE_HEIGHT, 0, 0, 0);

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -IMAGE_HEIGHT, self.view.frame.size.width, IMAGE_HEIGHT)];
    imageView.image = [UIImage imageNamed:@"avator_smaller.jpg"];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    [self.tableView addSubview:imageView];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CGFloat y = scrollView.contentOffset.y;
    //实际上只是把图片的高度放大了
    if (y < -IMAGE_HEIGHT) {
        CGRect frame = imageView.frame;
        frame.origin.y = y;
        frame.size.height =  -y;
        imageView.frame = frame;
    }

}

DEMO下载

二、ScrollView中实现图片下拉变大

一定需要设置ScrollView的ContentSize的大小,才会触发scrollView滚动的方法。

- (void)viewDidLoad {
    [super viewDidLoad];

    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height-20)];
    _scrollView.delegate = self;
    [self.view addSubview:_scrollView];

    _scrollView.contentInset = UIEdgeInsetsMake(IMAGE_HEIGHT, 0, 0, 0);
    _scrollView.contentSize = CGSizeMake(0, 1000);

    imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -IMAGE_HEIGHT, self.view.frame.size.width, IMAGE_HEIGHT)];
    imageView.image = [UIImage imageNamed:@"avator_smaller.jpg"];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    [self.scrollView addSubview:imageView];

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{

    CGFloat y = scrollView.contentOffset.y;
    if (y < -IMAGE_HEIGHT) {
        CGRect frame = imageView.frame;
        frame.origin.y = y;
        frame.size.height =  -y;
        imageView.frame = frame;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长沙火山

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值