下拉放大效果非常常见, 做起来也比较简单, 主要思路如下:
- 需要下拉放大的图片最好是add进tableview的最底部,而不要作为tableview的头部
- 设置图片的y值为一个负数(我设置的是“-图片的高度”),这样图片的底部就是处于屏幕的顶部
- 设置tableview的内边距contentInset, 设置为图片高度的一半,这样图片就会露出一半
- 在UIScrollViewDelegate代理方法中计算下拉的偏移量, 根据偏移量设置图片缩放的比例, 也可以通过修改图片的宽高达到效果(设置图片的内容模式)
#import "ViewController.h"
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
float ratio = 3;
CGFloat imageWidth = 415;
CGFloat imageHeight = 260;
@interface ViewController () <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *topImageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self setupSubViews];
}
- (void)setupSubViews
{
UIImageView *topImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"13.jpg"]];
topImageView.contentMode = UIViewContentModeScaleAspectFill;
topImageView.frame = CGRectMake(0, -imageHeight, imageWidth, imageHeight);
_topImageView = topImageView;
[self.tableView insertSubview:topImageView atIndex:0];
self.tableView.contentInset = UIEdgeInsetsMake(imageHeight / 2, 0, 0, 0);
[self.view addSubview:_tableView];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reuseId = @"reuseId";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseId];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseId];;
}
cell.textLabel.text = [NSString stringWithFormat:@"下拉有惊喜哦%ld", indexPath.row];
return cell;
}
#pragma mark - UIScrollViewDelegate(缩放)
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetY = scrollView.contentOffset.y + imageHeight / 2;
if (offsetY > 0) {
return;
}
NSLog(@"offsetY = %f", offsetY);
CGFloat scale = -offsetY / kScreenHeight * ratio;
_topImageView.transform = CGAffineTransformMakeScale(1 + scale, 1 + scale);
}
#pragma mark - UIScrollViewDelegate(修改高度)
- (UITableView *)tableView
{
if (!_tableView) {
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
_tableView.dataSource = self;
_tableView.delegate = self;
_tableView.rowHeight = 50;
}
return _tableView;
}
@end
效果如下:
