zoukankan      html  css  js  c++  java
  • iOS 两种不同的图片无限轮播

    代码地址如下:
    http://www.demodashi.com/demo/11608.html

    前记

    其实想写这个关于无限轮播的记录已经很久很久了,只是没什么时间,这只是一个借口,正如:时间就像海绵,挤一挤还是有的。记得在刚刚开始工作的时候,第一个接触到比较酷的东西就是图片的无限轮播,那还是三年多前的一个火辣辣的夏天,其实可以说是秋天,然而天府之国的成都并没有....下面我们进入正题吧

    轮播的方式

    到目前为止,我见过的轮播方法,大概有那么三种,由于轮播嘛,所以肯定都是在UIScrollView的基础上

    1、在UIScrollView上添加N+2UIImageView
    2、在UIScrollView上添加固定的3UIImageView
    3、利用重用机制中的UICollectionView来实现

    原理

    下面,就简单阐述下三种不同方法的原理,以及其优缺点

    • 第一种:其原理图大概如下

    N+1.png

    该方案的原理是在UIScrollView 上添加N+2UIImageView ,比如上图中,有三张需要轮播的图,那么我们可以添加五个UIImageViewUIScrollView上,图片赋值的顺序如上图,当我们向左滑动到最左的时候,即到3这个位置的时候,调用setContentOffset ,让其滚动到右边的3这个位置,当然不能调用动画,这样肉眼是看不出来的,给我们造成一种视角错觉,如果是向右滑动到最右边的1,其原理也是一样的。

    优点:容易理解
    缺点:如果有100个图片,那么我们岂不是要添加102个,这样的话,内存肯定是吃不消的把。

    • 第二种:其原理图大概如下

    3.png

    该方案的原理是在UIScrollView 上添加固定的3UIImageView ,在初始化的时候,分别如上图那样赋值,并且调用setContentOffset,让其居中。of course,这只是前奏,对比第一种方法,肯定在逻辑处理上复杂点。
    复杂逻辑,当我们向左或者向右滑动一张图片后,需要根据当前滚动的index来设置图片,并且由于滑动后UIScrollViewcontentOffset发生了改变,后续还需要处理一些其他逻辑。
    比如向左滑动的话,就到了最右边,这样,我们再向右就不能再滑动了,所以为了保证能继续滑动,我们需要在滑动结束的时候,设置contentOffset,使第二个UIImageView一直处于屏幕中间,除此之外,我们还需要重新设置图片,由于我们向左滑动,图中的2显示的图片其实是我们需要展示的,因为我们要设置contentOffset,这样2这个imageView就又移动到最右边去了,所以这时候我们设置图片,就要将1imageView设置为后面一张即2imageView的图片,将3imageView设置为1之前的图片,如此来实现循环。
    下面是部分代码

    //减速停止的时候
    -(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
    {
        _endOffsetX = scrollView.contentOffset.x;
        
        //给imageview赋值
        [self loadImage];
        //改变offset
        [_scrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];
        
        if (self.didScrollToIndexBlock)
        {
            self.didScrollToIndexBlock(_currentIndex);
        }
    }
    

    效果如如下:

    轮播1.gif

    优点:相比第一种,内存上开销很小
    缺点:代码稍多,理解复杂,如果非常快速滑动,可能会出现最右或者最左滑不动,因为scrollViewDidEndDecelerating还未执行

    • 第三种:其原理图大概如下

    collectionview.png
    其原理很简单,主要是根据UICollectionView 的重用机制,通过创建许多个cell,然后来实现,当然,内存就不用去考虑了,因为这个是通过重用机制实现的。

    下面是部分代码

    创建UICollectionView

    - (void)addCollectionView
    {
        self.collectionFlowLayout = [[UICollectionViewFlowLayout alloc] init];
        self.collectionFlowLayout.minimumLineSpacing = 0;
        self.collectionFlowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        self.collectionFlowLayout.itemSize = self.bounds.size;
        
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.collectionFlowLayout];
        self.collectionView.dataSource = (id)self;
        self.collectionView.delegate = (id)self;
        self.collectionView.pagingEnabled = YES;
        self.collectionView.showsVerticalScrollIndicator = self.collectionView.showsHorizontalScrollIndicator = NO;
        [self.collectionView registerClass:[GLRollingScrollviewCell class] forCellWithReuseIdentifier:GLRollingScrollviewCellId];
        [self addSubview:self.collectionView];
    }
    
    

    自动滚动定时器部分

    //开启定时器
    - (void)startTimer
    {
        [self cofigTimer];
    }
    
    //关闭定时器
    - (void)pauseTimer
    {
        if (self.timer)
        {
            CFRunLoopTimerInvalidate(self.timer);
            CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), self.timer, kCFRunLoopCommonModes);
        }
    }
    
    //配置定时器
    - (void)cofigTimer
    {
        if (self.imageUrlArray.count <= 1)
        {
            return;
        }
        
        if (self.timer)
        {
            CFRunLoopTimerInvalidate(self.timer);
            CFRunLoopRemoveTimer(CFRunLoopGetCurrent(), self.timer, kCFRunLoopCommonModes);
        }
        
        __weak typeof(self)weakSelf = self;
        
        CFRunLoopTimerRef time = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()+ _intervalTimer, _intervalTimer, 0, 0, ^(CFRunLoopTimerRef timer) {
            [weakSelf autoScroll];
        });
        self.timer  = time;
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), time, kCFRunLoopCommonModes);
    }
    
    //自动滚动
    - (void)autoScroll
    {
        NSInteger currentIndex = (self.collectionView.contentOffset.x + self.collectionFlowLayout.itemSize.width * 0.5) / self.collectionFlowLayout.itemSize.width;
        NSInteger toIndex = currentIndex + 1;
        
        NSIndexPath *indexPath = nil;
        if (toIndex == self.totalNumber)
        {
            toIndex = self.totalNumber * 0.5;
            indexPath = [NSIndexPath indexPathForRow:toIndex inSection:0];
            [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        }
        else
        {
            indexPath = [NSIndexPath indexPathForItem:toIndex inSection:0];
            
            [self.collectionView scrollToItemAtIndexPath:indexPath
                                        atScrollPosition:UICollectionViewScrollPositionNone
                                                animated:YES];
        }
    }
    

    手动滑动时避免和定时器冲突

    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
        [self pauseTimer];
    }
    
    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
    {
        [self startTimer];
    }
    

    计算当前index

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        if (self.totalNumber == 0)
        {
            return;
        }
        
        NSInteger currentIndex = (scrollView.contentOffset.x + self.collectionView.frame.size.width * 0.5) / self.collectionView.frame.size.width;;
        
        currentIndex = currentIndex % self.imageUrlArray.count;
        
        
        CGFloat x = scrollView.contentOffset.x - self.collectionView.frame.size.width;
        NSUInteger index = fabs(x) / self.collectionView.frame.size.width;
        CGFloat fIndex = fabs(x) / self.collectionView.frame.size.width;
        
        //下面的第二个条件 可以确保 尽量一次去执行block 而不多次
        if (self.rollingDidScrollBlock && fabs(fIndex - (CGFloat)index) <= 0.00001)
        {
    //            NSLog(@" 打印信息:%ld",(long)currentIndex);
            
            self.rollingDidScrollBlock(currentIndex);
        }
        
    }
    

    在上面代理scrollViewDidScroll 中,有个关键地方,大家都知道scrollViewDidScroll 只要再滑动过程中就会一直执行,为了避免多次执行,而导致内存问题,我们希望的是尽可能的在滑动结束的时候来执行,所以这个地方,加了一句判断fabs(fIndex - (CGFloat)index) <= 0.00001,因为在结束的时候,这两个值的差应该很小,几乎可以为0。所以,这样就不会导致代码在此多次执行。

    项目文件截图:

    文章结尾

    针对上的三种方法,我对后面两种方式写了两个简单的demo,希望对大家有帮助。iOS 两种不同的图片无限轮播

    代码地址如下:
    http://www.demodashi.com/demo/11608.html

    注:本文著作权归作者,由demo大师代发,拒绝转载,转载需要作者授权

  • 相关阅读:
    JSON连载java目的
    2014百度之星预赛(第二场)——Best Financing
    推断值的数组
    Codeforces 437E The Child and Polygon(间隔DP)
    ruby简单的基本 3
    定义和实现二叉树
    C++11并行编程-条件变量(condition_variable)详细说明
    【Bootstrap】自己主动去适应PC、平面、手机Bootstrap网格系统
    使用代码自定义UIView注意一二三
    关于 android 中 postDelayed方法的讲解
  • 原文地址:https://www.cnblogs.com/demodashi/p/8509284.html
Copyright © 2011-2022 走看看