iOS UI 基础开发中的种种...00『 基础知识 』

拖动 tableView 来缩放顶部图片

2016-05-30  本文已影响577人  TobyoTenma

在 UITableView 的头部添加一个 imageView,通过拉动 tableView 来放大缩小这个 imageView.

效果如下:

20160527220410771.gif

实现步骤:

1.创建 tableView 的 headerView,并设置其frame,将背景色改为 clearColor;
2.创建一个 UIImageView,与 tableViewHeaderView 一样大小;
3.创建一个 UIView,与tableView 一样大小;
4.将 UIImageView 添加到 UIView 上,并将 UIView 设置为 tabelView 的 backgroundView 属性

经过以上 4 个步骤的设置,就以保正 UIImage 始终在 tableView 下面,不会遮住 tableView;

下面我们来看看代码的实现:

 #import "TTAMineTableViewController.h"

@interface TTAMineTableViewController ()
@property (strong,nonatomic) UIImageView *imageView;
@end

@implementation TTAMineTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // 创建一个 imageView 一张图,大小与 tableHeaderView 大小相同
    UIImage *image = [UIImage imageNamed:@"hh"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.frame = CGRectMake(0, 44, self.view.frame.size.width, 300);

    // 让图片内容按原图的比例放缩
    imageView.contentMode = UIViewContentModeScaleAspectFill;

    // 声明一个属性,后面改变 imageView 大小的时候要用到
    self.imageView = imageView;

    // 创建一个 背景 View,与屏幕一样大小
    UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];

    // 将 imageView 加到 bgView 上
    [bgView addSubview:imageView];
    // 将 bgView 设置为 tableView 的 backgroundView 属性
    self.tableView.backgroundView = bgView;

    // 设置 tableHeaderView 并将背景色设置为透明
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 300)];
    [self.tableView.tableHeaderView setBackgroundColor:[UIColor clearColor]];
}

 #pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"老司机老司机%zd",indexPath.row];
    return cell;
}

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

    // 修改 imageView 的高
    CGRect frame = self.imageView.frame;

    CGFloat offsetY = self.tableView.contentOffset.y;

    if(offsetY > 0){
        frame.origin.y = -offsetY;
    }else{
        // 向下拉时,放大,同时将 imageView 的顶部放在 y = 0 的位置
        frame.origin.y = 0;
        // 修改 imageView 的高度,就可以放大图片了
        frame.size.height = 300 - offsetY * 2;
    }
    self.imageView.frame = frame;
}
@end
上一篇 下一篇

猜你喜欢

热点阅读