iOS開發-tableView頂部圖片拉伸

大家可能注意到一些app的tableView的頂部圖片,會隨着你拉伸而跟着拉伸變大,下面這是我的一些想法

原圖


效果圖


下面附上代碼吧,這裏的圖片不是添加在tabview的header上

#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height
#define TOP 200 //頂部預留

#import "ViewController.h"

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITableView *tableV;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self creatTableView];
}

- (void)creatTableView
{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) style:UITableViewStylePlain];
    self.tableV.contentInset = UIEdgeInsetsMake(TOP, 0, 0, 0);
    
    self.tableV.delegate    = self;
    self.tableV.dataSource  = self;
    
    //創建頂部圖片
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, -TOP, SCREEN_W, TOP)];
    imageView.tag = 1000;
    
    //更改圖片顯示模式 根據圖片原有尺寸進行顯示 將多餘部分切除
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    
    //多餘部分隱藏
    imageView.clipsToBounds = YES;
    
    imageView.image = [UIImage imageNamed:@"pic"];
    
    [self.view addSubview:_tableV];
    [self.tableV addSubview:imageView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    float offSet = scrollView.contentOffset.y;
    
    if (offSet < -200)
    {
        UIImageView * tempImageView = (UIImageView*)[self.view viewWithTag:1000];
        
        CGRect f = tempImageView.frame;
        //保持圖片原點仍爲屏幕左上方
        f.origin.y = offSet;
        //保證圖片根據滑動高度拉伸
        f.size.height = -offSet;
        //給圖片重新設置座標
        tempImageView.frame = f;
    }
}

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cell = @"cell";
    UITableViewCell *myCell = [tableView dequeueReusableCellWithIdentifier:cell];
    if (!myCell) {
        myCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cell];
    }
    myCell.textLabel.text = @"我是 cell";
    return myCell;
}

@end






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章