前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >轮播图实现的三种方式

轮播图实现的三种方式

作者头像
莫空9081
发布2023-10-16 09:36:31
2860
发布2023-10-16 09:36:31
举报
文章被收录于专栏:iOS 备忘录

轮播图实现的三种方式

假设有5张图片,分别是:12345,实现轮播图

方法1:用scrollView加NSTimer实现,思路:12345五张图片,实现轮播,我添加两张,变成5123451,当滑到最后一个1时,无动画位移回第一个1;当倒着滑到5时,无动画回最后的5。

难点在于:给定数组的个数,及两个边界的判断

方法2:用collectionView加NSTimer实现,思路:12345五张图片,对应collectionView的1个section,即一个section有5个row;至于有多少个section,尽量设置的大一些,eg:100;(collectionView有重用机制)所以不用担心内存问题。

难点在于:滑动的逻辑处理;如果你把section设置的非常大,就不用担心倒着滑的问题,毕竟不是每个人都那么闲。

代码语言:javascript
复制
- (void)nextPage:(id)sender {
    // 1. 得到当前正在显示的cell的indexPath,(只有一个)
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    
    // 2. 得到YYMaxSections/2对应的section的indexPath,显示此indexPath对应的cell
    NSIndexPath *currentIndexPathReset = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:YYMaxSections/2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathReset atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    // 3. 如果当前section的row未显示完全,则row+1,否则section+1,row置为0
    NSInteger nextItem = currentIndexPathReset.item + 1;
    NSInteger nextSection = currentIndexPathReset.section;
    if (nextItem == self.dataArray.count) {
        nextItem = 0;
        nextSection++;
    }
    
    // 4. 位移显示效果
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}

方法3:用scrollView加NSTimer实现,12345,只用3个imageView,每次滑动的时候,始终保证下一个是居中,eg:512,123,234,当你从2滑到3的时候,结束后位移从123变为到234;

代码:https://github.com/mokong/CircleView 注:代码里只有前两种方法,没有第三种,大家可以自己百度第三种的实现代码;

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-01-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 轮播图实现的三种方式
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档