首页 > 代码库 > 表的头视图下拉放大效果

表的头视图下拉放大效果

ViewController.h

@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
{
    UIImageView *_imageView;
}

ViewController.m

<p>#import "ViewController.h"</p>
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //创建表视图
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor clearColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    
    //创建视图
    _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
    _imageView.image = [UIImage imageNamed:@"image1.jpg"];
    [self.view insertSubview:_imageView belowSubview:tableView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 150)];
    headView.backgroundColor = [UIColor clearColor];
    tableView.tableHeaderView = headView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 40;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *iden = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:iden];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:iden];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"第%d行",indexPath.row];
    
    return cell;
}

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

    //获取到视图Y方向的偏移量
    CGFloat offsetY = scrollView.contentOffset.y;
    CGRect frame = _imageView.frame;
    //向上滑动
    if (offsetY > 0) {
        frame.origin.y = - offsetY;
        _imageView.frame = frame;
    }else {
        //向下滑动
        
        //1.获取拉伸后图片的高度
        CGFloat height = 150 + ABS(offsetY);
        
        //图片原来的高度/图片原来的宽度 = 图片放大后的高度/图片放大后的宽度
        //150/320 = height/x
        //2.获取图片放大后的宽度
        CGFloat width = 320 *height/150;
        
        //3.修改imageView的frame
        _imageView.frame = CGRectMake(-(width-320)/2, -(height-150)/2, width, height);
        
    }
    
}

@end


表的头视图下拉放大效果