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;
}

实现起来比较简单,网上有各种各样的版本,这两种的方式算是最简单的实现~

posted @   Fly_Elephant  阅读(1869)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
历史上的今天:
2015-01-23 iOS开发-照片选择
点击右上角即可分享
微信分享提示