經驗之談—實現圖片下拉放大的效果

  • 這裏我們主要是用一下,如何能保持原來的圖片的寬高比來輕鬆的實現放大的效果,主要的是UIViewContentModeScaleAspectFill這個起的效果:

  • 我們用tableView來展示這個效果吧


  • 我們這裏並沒有計算圖片的寬高比,直接用UIViewContentModeScaleAspectFill來實現

#import "ViewController.h"
const CGFloat ZYTopViewH = 350;
@interface ViewController ()
@property(nonatomic,weak)UIImageView *topView;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];


    self.tableView.contentInset = UIEdgeInsetsMake(ZYTopViewH * 0.5, 0, 0, 0);
    UIImageView *topView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"biaoqingdi"]];
    topView.frame = CGRectMake(0, -ZYTopViewH, 375, ZYTopViewH);

    topView.contentMode = UIViewContentModeScaleAspectFill;

    [self.tableView insertSubview:topView atIndex:0];

    self.topView = topView;

}
  • 實現tableView的數據源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
       cell =  [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }

    cell.textLabel.text = [NSString stringWithFormat:@"test---%zd",indexPath.row];

    return cell;
}
  • 最後用scrollViewDidScroll來監聽拖動事件
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;

    CGFloat offsetH = -ZYTopViewH * 0.5 - offsetY;

    if (offsetH < 0) return;

    CGRect frame = self.topView.frame;
    frame.size.height = ZYTopViewH + offsetH;
    self.topView.frame = frame;


}

看一下效果:
下拉放大


這裏主要是講UIViewContentModeScaleAspectFill的作用,但是我覺得這個demo中也牽扯到一些東西,也順便講講

  • 爲什麼將UIImageView採用
[self.tableView insertSubview:topView atIndex:0];

這種方式來添加,其實一開始我也是直接讓UIImageView作爲headerView的,但是作爲headerView的話,就不能讓圖片一開始顯示一部分在外面了,也不好控制

  • 然後偏移量等,就自然而然的想到了。多嘗試,就多收穫。。。。
發佈了177 篇原創文章 · 獲贊 111 · 訪問量 47萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章