iOS tableView实现顶部图片拉伸效果

时间:2021-05-20

大家可能注意到一些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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章