iOS开发-UITableView滑动视差

视差滚动是指让多层背景以不同的速度移动,形成立体的运动效果,在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,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值