视差滚动是指让多层背景以不同的速度移动,形成立体的运动效果,在Web上应用的比较多,App中倒是见的相对比较少,主要在UITableView中的应用的比较多,尤其是当整个UITableViewCell的背景是图片的时候,描述内容较少,滑动视差可以增强视觉效果,可以考虑使用,先来简单的看一下效果:
实现起来也比较简单,UITableView定义:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#pragma mark - UITablViewDataSource -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1;
} -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return [self.dataSource count];
} -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ MainTableViewCell *mainCell=[tableView dequeueReusableCellWithIdentifier:CELLIDENTIFIER forIndexPath:indexPath];
NSString *desc=[NSString stringWithFormat: @"FlyElephant-%ld" ,indexPath.row];
[mainCell setBackImage:self.dataSource[indexPath.row] description:desc];
return mainCell;
} #pragma mark - UITableViewDelegate -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ return 150;
} |
滑动的时候修改单元格偏移量:
1
2
3
4
5
6
7
8
9
10
|
#pragma mark - UIScrollViewDelegate -( void )scrollViewDidScroll:(UIScrollView *)scrollView{
CGPoint offset=self.tableView.contentOffset;
for (MainTableViewCell *cell in self.tableView.visibleCells) {
//方式1
// [cell setImagOffset:offset tableView:self.tableView]; //方式2
[cell setAdjustOffset:(cell.frame.origin.y-offset.y)];
}
} |
MainTableViewCell定义:
1
2
3
4
5
6
7
8
9
10
11
|
@ interface MainTableViewCell : UITableViewCell
-( void )setBackImage:(NSString *)imageName description:(NSString *)desc;
//视差滑动方式1 -( void )setImagOffset:(CGPoint)contentOffset tableView:(UITableView *)tablView;
//视差滑动方式2 -( void )setAdjustOffset:(CGFloat)offset;
@end |
滑动视差调用方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
-( void )setImagOffset:(CGPoint)contentOffset tableView:(UITableView *)tablView{
//偏移量
CGFloat cellOffset = self.frame.origin.y - contentOffset.y;
// 偏移量+单元格高度/tableview高度+单元格高度
CGFloat percent = (cellOffset+self.frame.size.height)/(tablView.frame.size.height+self.frame.size.height);
//偏移比例(0-1)
CGFloat extraHeight = self.frame.size.height*OFFSET_RATE;
CGRect frame=self.backImageView.frame;
frame.origin.y=extraHeight*percent;
self.backImageView.frame=frame;
} -( void )setAdjustOffset:(CGFloat)offset{
CGRect frame = self.backImageView.frame;
frame.origin.y = (offset / 15.0);
self.backImageView.frame = frame;
} |
实现起来比较简单,网上有各种各样的版本,这两种的方式算是最简单的实现~
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/5152828.html,如需转载请自行联系原作者