最近感覺UITableview頭部帶有圖片,并且下拉時圖片放大這種效果非常炫酷,所以動手實現了一下,效果如下圖:
1.gif
實現原理很簡單,就是在UITableview上邊添加一個圖片子視圖,在tableview拖動的時候動態的改變圖片的frame,就可以實現這個效果。
步驟如下:
1. 布置UITableview
UITableview的設置和正常一樣,沒有什么需要注意的地方,我這里是直接在storyboard里面拖的,代碼如下:
@property (weak, nonatomic) IBOutlet UITableView *tableView;
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell_id"];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 30;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell_id" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"%ld--%ld", indexPath.section, indexPath.row];
return cell;
}
2. 布置圖片
布置圖片的時候,我們首先要通過設置UITableview的內容偏移來為圖片視圖留出位置,這里我們的圖片高度暫定為200。
self.tableView.contentInset = UIEdgeInsetsMake(kHEIGHT, 0, 0, 0);
接下來就是布置圖片,圖片要放在內容視圖之上,所以圖片的縱向位置應該為負。
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -kHEIGHT, [UIScreen mainScreen].bounds.size.width, kHEIGHT)];
imageView.image = [UIImage imageNamed:@"IMG_0767.JPG"];
imageView.contentMode = UIViewContentModeScaleAspectFill;
imageView.tag = 101;
[self.tableView addSubview:imageView];
需要注意的是,圖片的** contentMode 必須設置為 UIViewContentModeScaleAspectFill ** , 這樣才能保證圖片在放大的過程中高和寬是同時放大的。
3. 拖動事件的處理
我們都知道,UITableview屬于可以滑動的控件,所以它的父類是UIScrollView,所以我們就可以在滑動事件中做出一些處理。
在滑動的時候,一旦判定是下拉狀態并且是從大于圖片高度的地方下拉的,那么我們就要動態的改變圖片的縱向位置和圖片的高度(由于設置了contentMode,所以寬度自己會變化),最終實現所需要的效果。
代碼如下:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGPoint point = scrollView.contentOffset;
if (point.y < -kHEIGHT) {
CGRect rect = [self.tableView viewWithTag:101].frame;
rect.origin.y = point.y;
rect.size.height = -point.y;
[self.tableView viewWithTag:101].frame = rect;
}
}