下拉放大的效果在很多電商類網站上都有應用,一般的情況是在tableView的最頂端放置1個UIView 或者UIScrollView控件,在tableView向下拖拽的時候,圖片會從中心點向下產生放大的效果.下面就說一下兩種效果略有不同 下拉放大效果的實現思路.備查.
兩種下拉放大的實現思路:
第一種
首先在tableView的聲明1個屬性就是頂部的那個需要放大的imageView
#import "GZDTableViewController.h"
@interface GZDTableViewController ()
//頂部需要放大的View
@property (weak,nonatomic) UIImageView *topView;
@end
@implementation GZDTableViewController
在ViewDidLoad方法中加載這個view
- (void)viewDidLoad {
[super viewDidLoad];
//加載圖片
UIImage *foodImage = [UIImage imageNamed:@"food"];
//通過圖片創建imageView
UIImageView *topView = [[UIImageView alloc] initWithImage:foodImage];
//設置圖片的填充模式
//等比例縮放,圖片不會變形.填充整個父控件
topView.contentMode = UIViewContentModeScaleAspectFill;
//設置頂部View的frame
topView.frame = CGRectMake(0, -foodImage.size.height, foodImage.size.width, foodImage.size.height);
//為了不擋住tableView的cell內容所以將頂部的View插入到最下面的一層.
[self.tableView insertSubview:topView atIndex:0];
//給屬性賦值
self.topView = topView;
//設置tableView 的內邊距 這樣頂部的view 就能夠完全的展示出來,不會擋住cell.
self.tableView.contentInset = UIEdgeInsetsMake(foodImage.size.height , 0, 0, 0);
}
tableView 繼承自scrollView ,實現scrollView的代理方法監聽手指的拖拽
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//由于scrollView 向下拖拽的contentOffset.y的值是負數.并且設置了contentInsets,這里這樣設置可以將offset的初始值設置為0,下拉時為正數,方便判斷.
CGFloat offset = -(scrollView.contentOffset.y + self.topView.image.size.height);
//image的寬高比
CGFloat scale = self.topView.image.size.width / self.topView.image.size.height;
//如果是向上拖動 返回.
if (offset < 0) return;
//取出topView的frame
CGRect frame = self.topView.frame;
//x值向左邊移動-offset的距離
frame.origin.x = -offset;
//由于在viewDidLoad方法中設置了topView 的圖片填充模式,所以寬度拉伸之后,高度也會相應的拉伸.
frame.size.width =(self.topView.image.size.height +2*offset) *scale;
//重新賦值
self.topView.frame = frame;
最后實現效果
basic.gif
另外一種效果是頂部的圖片顯示一半,在下拉的時候緩慢的將圖片頂部沒有顯示出來的部分 顯示出來,并且放大,代碼更加簡單
同樣的項目
在ViewDidLoad方法中將tableView的內邊距設置只有圖片大小的一半
#warning 這里的frame值 修改到只顯示一半
self.tableView.contentInset = UIEdgeInsetsMake(foodImage.size.height *0.5 , 0, 0, 0);
在scrollView的代理方法中
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
#warning 由于contentInset設置的是圖片高度的一半,所以此處也設置為一半的高度
CGFloat offset = -(scrollView.contentOffset.y + self.topView.image.size.height *0.5);
if (offset < 0) return;
//改變topView的frame
CGRect frame = self.topView.frame;
//因為設置了topView的填充模式,所以只修改topView的高度就可以實現效果,寬度會等比例自適應,并且保證圖片的中心始終在父控件的中心顯示.
frame.size.height = self.topView.image.size.height + offset;
self.topView.frame = frame;
最終效果
1.gif
這種方式更加簡單,但是一般頂端圖片的大小都僅僅占據頂部的一小塊區域,使用這種方式加載的圖片只要用戶手指拖拽的夠久 就能夠看到最后面的背景.