您的位置:首页 > 产品设计 > UI/UE

[iOS]实现UITableView头部带有图片并且下拉图片放大效果

2016-05-12 09:49 791 查看
最近感觉UITableview头部带有图片,并且下拉时图片放大这种效果非常炫酷,所以动手实现了一下,

效果如下图:



1.gif

实现原理很简单,就是在UITableview上边添加一个图片子视图,在tableview拖动的时候动态的改变图片的frame,就可以实现这个效果。

步骤如下:

1. 布置UITableview
UITableview的设置和正常一样,没有什么需要注意的地方,我这里是直接在storyboard里面拖的,代码如下:

@property (weak, nonatomic) IBOutlet UITableView *tableView;
[/code]
self.tableView.delegate = self;
self.tableView.dataSource = self;
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell_id"];
[/code]
- (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;
}
[/code]
2. 布置图片
布置图片的时候,我们首先要通过设置UITableview的内容偏移来为图片视图留出位置,这里我们的图片高度暂定为200。

self.tableView.contentInset = UIEdgeInsetsMake(kHEIGHT, 0, 0, 0);
[/code]
接下来就是布置图片,图片要放在内容视图之上,所以图片的纵向位置应该为负。

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];
[/code]
需要注意的是,图片的 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;
}
}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios uitableview