前言
在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;
}
}
二、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;
}
}