ios一个简单易用的轮播图的封装

作者: mark666 | 来源:发表于2016-06-07 14:30 被阅读1153次
    效果图

    本文gitoschia的地址

    https://git.oschina.net/mark6/scrollLoop.git

    本文gitHub地址

    https://github.com/markdashi/scrollLoop

    上一周在简书首页投稿看到了很多关于轮播图的文章,每一篇我都点进去看了一下,很可惜我看到的都是基于ScrollView的封装,好一点的会考虑到复用,就是放3个imageView来实现的图片的轮播,加上定时器。我很不理解的是,既然能考虑到复用的朋友为什么没有考虑到UICollecionView呢?好吧,我暂且相信你对UICollecionView不太熟悉,现在我将自己的思路及实现分享一下,供有兴趣的朋友参考一下。
    首先我说一下UICollecionView的优点
    1.首先不需要考虑复用,在整个过程中只会创建两个cell.
    2.性能高,通用性强。

    其次说一下实现的主要思路,
    继承UIView定义一个scrollLoopView类,将UICollecionView添加到整个类subViews,定义数据源为传进来数组 * 10,开始定义collectionView为其中心位置,当滑动index超过数据源count时让它又从中心开始。当然这只是一个简单的思路,中间会有很多小细节处理,具体看代码。

    #import <UIKit/UIKit.h>
    
    
    @class scrollLoopView;
    @protocol scrollLoopViewDelegate <NSObject>
    
    @optional
    
    - (void)scrollLoopView:(scrollLoopView *)scrollLoopView didSelectItemAtIndex:(int)index;
    
    
    @end
    
    @class scrollLoopViewDelegate;
    @interface scrollLoopView : UIView
    
    @property (nonatomic, strong) NSArray *images;
    @property (nonatomic, weak) id<scrollLoopViewDelegate>delegate;
    @end
    
    

    在其initWithFrame写相应的配置

    - (instancetype)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame]) {
            [self initsConfig];
            
        }
        
        
        return self;
    }
    /**
     *  配置基本框架
     */
    - (void)initsConfig
    {
    
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _flowLayout = layout;
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:layout];
        collectionView.backgroundColor = [UIColor clearColor];
        collectionView.delegate  = self;
        collectionView.dataSource = self;
        collectionView.pagingEnabled = YES;
        collectionView.showsHorizontalScrollIndicator = NO;
        [collectionView registerNib:[UINib nibWithNibName:@"MyCollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:identify];
        _collectionView = collectionView;
        [self addSubview:collectionView];
        
        UIPageControl *pageControl = [[UIPageControl alloc] init];
        _pageControl = pageControl;
        
        [self addSubview:pageControl];
        
    
    }
    
    

    这里一定要注意的是,在layoutSubView中,定义_flowLayout.itemSize尺寸,否则会报错。

    - (void)layoutSubviews
    {
        [super layoutSubviews];
        
        _flowLayout.itemSize = self.frame.size;
        _collectionView.frame = self.bounds;
        
    //这里是为了collection起始位置居中,而animated一定为NO,否则你会遇到你不想要效果
        if (_collectionView.contentOffset.x == 0 && _totalImageCount) {
            
            int tarIndex = _totalImageCount * 0.5;
            
            [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:tarIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
        }
        
      //_pageControl 的frame是相对固定的
        _pageControl.frame = CGRectMake((self.frame.size.width - 100)/2, self.frame.size.height - 30, 100, 20);
     
    }
    
    

    实现自动轮播少不了的是定时器NSTimer

    - (void)setupTimer{
    
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:NSTimeIntervalDefault target:self selector:@selector(AutoScroll) userInfo:nil repeats:YES];
        _timer = timer;
        [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
    }
    - (void)AutoScroll
    {
        
        int currentIndex = [self currentIndex];
    
        int targetIndex = currentIndex + 1;
        if (targetIndex >= _totalImageCount) {
            
            targetIndex = _totalImageCount * 0.5;
            [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
            return;
        }
    
        [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:targetIndex inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    
    }
    //当前第几页
    - (int)currentIndex{
    
        if (_collectionView.frame.size.width == 0) {
            return 0;
        }
        int index = 0;
        
        index = (_collectionView.contentOffset.x + _flowLayout.itemSize.width * 0.5) /_flowLayout.itemSize.width;
    
        return index;
    }
    
    

    而定时器在哪里添加呢???有心的朋友可以不往下看,自己独立思考一下。

    - (void)setImages:(NSArray *)images
    {
        _images = images;
        _totalImageCount =  _images.count *10;
        if (images.count != 1) {
            [self setupTimer];
            _pageControl.numberOfPages = images.count;
        }
    
        [_collectionView reloadData];
    }
    //当设置数据源的时候,只要传进来的数据不为空,就设置定时器
    

    接下来最最要的UICollectionView的代理方法

    #pragma mark - UICollectionViewDataSource
    
    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
    {
        return _totalImageCount;
    }
    
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    
        MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        
        long index = indexPath.item % self.images.count;
            
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.images[index]]];
        cell.label.text = [NSString stringWithFormat:@"%zd",index];
        
        return cell;
    }
    
    

    大家看代码,可以发现上面主要的加载的是网络图片,当然你可以判断传进来数组中字符串的类型,如果是本地,就采用imageNamed方法来加载

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    
        MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
        
        long index = indexPath.item % self.images.count;
         cell.label.text = [NSString stringWithFormat:@"%zd",index];
        if (![self.images[index] hasPrefix:@"http"]) {
            cell.imageView.image =[UIImage imageNamed:self.images[index]];
            return cell;
        }
        
        [cell.imageView sd_setImageWithURL:[NSURL URLWithString:self.images[index]]];
       
        
        return cell;
    }
    
    

    点击的相应事件如下处理

    #pragma mark - UICollectionViewDelegate
    
    - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
    {
    
        if ([self.delegate respondsToSelector:@selector(scrollLoopView:didSelectItemAtIndex:)]) {
            
            [self.delegate scrollLoopView:self didSelectItemAtIndex:(int)indexPath.item % self.images.count];
        }
        
    }
    

    pageControl联动

    - (void)scrollViewDidScroll:(UIScrollView *)scrollView
    {
        int index = [self currentIndex];
        _pageControl.currentPage = index % self.images.count;
        
    
    }
    

    这样呢我们这个类就简单的封装好了,使用起来更加简单,那个类使用,导入头文件

     scrollLoopView *loop = [[scrollLoopView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 300)];
     loop.delegate = self;
    loop.images =@[     @"http://web.img.chuanke.com/fragment/9d595bc8fb5bf049ce3db527ede08abc.jpg",
                        @"http://web.img.chuanke.com/fragment/d662adfaebdc9aa3dac4b04299aa48e1.jpg",
                        @"http://web.img.chuanke.com/fragment/8003092be7e6cc3222c760c89e74a20d.jpg",
                        ];
    [self.view addsubView:loop];
    

    优化部分

    - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
    {
        [self invalidateTimer];
    }
    
    - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
    {
        [self setupTimer];
    }
    //确保定时器不出错
    

    以上呢就是轮播的简单的实现,博主呢主要目的是给敢兴趣的朋友提一个主要思路,供大家参考,当然这个类优化的空间很大,可扩展的空间也很大,有好的建议的伙伴可以尽管留言。

    相关文章

      网友评论

      • __西门吹雪__:当轮播到第30个时,若此时用户改为手动,则无法滑到下一张,怎么解决
        mark666:@龙战神 别着急发评论,先试试再说
        d15eb9289fc7:这行么。。那我写成100000000也行么?不是这么说的吧,求解决,而且如__西门吹雪__所说:当轮播到30个的时候,轮播的动画不是向左滑动,而是直接闪出第一张图,这。。求解决。。
        mark666:@允许我发发呆 有人也反映了这个问题,你可以扩大数据源,x100
      • Caiflower:这样会有个缺陷,在第15个的时候会出现类似卡顿一下的现象,这个是因为设置滚动到指定位置没设置动画效果的原因,但是开了启动画效果就更不好了....解决方案貌似只能将cell的个数继续增加,比如_totalImageCount = _images.count * 100; 用户总不可能盯着看100个吧.. :grin: 或者楼主有更好的解决方案吗
        Caiflower:@mark666 :scream:
        mark666:@花菜ChrisCai 100是不错的处理方法
      • yourbigbug:非常好
      • 午夜大鸟王:用了scheduledTimerWithTimeInterval 为什么还要将timer再加到Runloop?
        mark666: @Wii_moz 为了循环
        午夜大鸟王:@mark666 感谢解答。 :blush: ,之前有看到资料是会添加到默认循环。所以平时没太注意!
        还有就是上面代码将imageArray的count 乘10 难道是为了方便取模运算吗? :smirk:
        mark666:@Wii_moz 简单说一下,这涉及到NSRunLoop的只是,程序之所以能一直运行是因为在一个循环里面,当创建一个N STimer时候,系统有可能不会将这个定时器添加到主循环中,这时候定时器可能会失效,所以安全起见会将定时器添加到主循环中,想要升入了解可以看看这方面的资料。
      • 那一处风景ljz:demo能不能发来
        mark666:@那一处风景ljz 去gitHub或者osChina上下载
      • 智多芯:确实没想到用UICollectionView。
        我给UIScrollView加了个category实现了轮播功能。原理简单地说就是,scroll view里面只用三个content view。当用户滚动scroll view时就更新scroll view,让content view分别显示新的图片,而scroll view始终显示中间那个content view。
        https://github.com/hulizhen/HLZInfiniteScrollView
        mark666:@智多芯 你这个是2两年前我做的土办法
      • 89aa02172f4f:有github地址吗??
        89aa02172f4f:@mark666 谢谢
        mark666:@ACEVinfol gitHub半天打不开,上传太慢,yu'shi于是乎上传到gitoschia上,https://git.oschina.net/mark6/scrollLoop.git
      • 2700c7d83bfd:能不能来github链接,你这里的代码有缺的。
        mark666:@温眸indu1g https://git.oschina.net/mark6/scrollLoop.git
        mark666:@温眸indu1g ok,明天传上去

      本文标题:ios一个简单易用的轮播图的封装

      本文链接:https://www.haomeiwen.com/subject/rnvcdttx.html