在 UITableView 的頭部添加一個(gè) imageView,通過拉動(dòng) tableView 來放大縮小這個(gè) imageView.
效果如下:
20160527220410771.gif
實(shí)現(xiàn)步驟:
1.創(chuàng)建 tableView 的 headerView,并設(shè)置其frame,將背景色改為 clearColor;
2.創(chuàng)建一個(gè) UIImageView,與 tableViewHeaderView 一樣大小;
3.創(chuàng)建一個(gè) UIView,與tableView 一樣大小;
4.將 UIImageView 添加到 UIView 上,并將 UIView 設(shè)置為 tabelView 的 backgroundView 屬性
經(jīng)過以上 4 個(gè)步驟的設(shè)置,就以保正 UIImage 始終在 tableView 下面,不會(huì)遮住 tableView;
下面我們來看看代碼的實(shí)現(xiàn):
#import "TTAMineTableViewController.h"
@interface TTAMineTableViewController ()
@property (strong,nonatomic) UIImageView *imageView;
@end
@implementation TTAMineTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 創(chuàng)建一個(gè) imageView 一張圖,大小與 tableHeaderView 大小相同
UIImage *image = [UIImage imageNamed:@"hh"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 44, self.view.frame.size.width, 300);
// 讓圖片內(nèi)容按原圖的比例放縮
imageView.contentMode = UIViewContentModeScaleAspectFill;
// 聲明一個(gè)屬性,后面改變 imageView 大小的時(shí)候要用到
self.imageView = imageView;
// 創(chuàng)建一個(gè) 背景 View,與屏幕一樣大小
UIView *bgView = [[UIView alloc] initWithFrame:self.view.frame];
// 將 imageView 加到 bgView 上
[bgView addSubview:imageView];
// 將 bgView 設(shè)置為 tableView 的 backgroundView 屬性
self.tableView.backgroundView = bgView;
// 設(shè)置 tableHeaderView 并將背景色設(shè)置為透明
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:@"老司機(jī)老司機(jī)%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{
// 向下拉時(shí),放大,同時(shí)將 imageView 的頂部放在 y = 0 的位置
frame.origin.y = 0;
// 修改 imageView 的高度,就可以放大圖片了
frame.size.height = 300 - offsetY * 2;
}
self.imageView.frame = frame;
}
@end