无限图片轮播器

  项目中很多时候会碰到这个需求,实现多张图片的无限循环轮转,以前做过,项目中几个地方的都用到了,当时没有封装,几个地方都拷贝几乎一样的代码,代码复用性不好,今天没事封装了一下,使用起来比较简单。

  首先,说说我实现循环轮转图片的思想,在UIScrollView中添加了3个UIImageView,并排排列,我们看到的永远只是第二个UIImageView,这样的话,你一直可以向左,向右滑动,当你向左滑动是,这是你滑动到了最后一个UIImageView不能在向左边滑动了,这时,我在后面悄悄的将第二个UIImageView图片设置为当前要显示的图片,调整UIScrollView的contentOffset属性,如:

[_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO](使用者根本感觉不出来这种变化)所以,此时,你看到的又是第二个UIImageView,所以此时你又可以向左滑动,当你向右边滑动时候处理类似,导致结果你可以向左边,右边无线循环轮转图片。

   今天闲着蛋疼,封装了一下,代码如下:

 JGCirculateSwitchImgView.h头文件

@interface JGCirculateSwitchImgView : UIView

@property(nonatomic,strong)NSArray *imgUrlArr;

@end

  头文件中只有一个需要设置的成员变量imgUrlArr数组,就是你要显示图片路径的数组,将通过这个数组访问图片。

JGCirculateSwitchImgView.m文件

typedef NS_ENUM(NSInteger, SwitchDirection)

{

//未成功旋转

   SwitchDirectionNone = -1,

//向右旋转图片

 SwitchDirectionRight = 0,

//向左训转图片

SwitchDirectionLeft = 1,

};

定义了SwitchDirection枚举,表示图片向左,向右轮转,或者什么也不做。

//默认5秒训转图片一次,可以根据需要改变

#define WiatForSwitchImgMaxTime 5

#import "JGCirculateSwitchImgView.h"

#import "UIImageView+WebCache.h"

@interface JGCirculateSwitchImgView ()

//底部UIScrollView

@property(nonatomic,weak)UIScrollView *contentScrollView;

//显示页码的UIPageControl控件

@property(nonatomic,weak)UIPageControl *pageControlView;

//用保存当前UIPageControl控件显示的当前位置

@property(nonatomic,assign)NSInteger currentPage;

//用于保存当前显示图片在图片urlArr数组中的索引

@property(nonatomic,assign)NSInteger currentImgIndex;

//UIScrollView上的三个UIImgaView这里通过3个UIImageView实现无限循环图片轮转

@property(nonatomic,weak)UIImageView *imgView1;

@property(nonatomic,weak)UIImageView *imgView2;

@property(nonatomic,weak)UIImageView *imgView3;

@property(nonatomic,assign)BOOL isDragImgView;

//SwitchDirection类型,用于保存滑动的方向

@property(nonatomic,assign)SwitchDirection swDirection;

@end

-(id)initWithFrame:(CGRect)frame

{

       if (self = [super initWithFrame:frame])

       {

             [self createContentScrollView];

             [self createPageControlView];

            //默认第一页

            _currentPage = 0;

           //默认显示第一张图片

           _currentImgIndex = 0;

          _isDragImgView = NO;

          _swDirection = SwitchDirectionNone;

      }

         return self;

}

创建UIScrollView代码

-(void)createContentScrollView

{

        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];

        scrollView.delegate = self;

        scrollView.showsHorizontalScrollIndicator = NO;

        scrollView.shouldGroupAccessibilityChildren = NO;

        scrollView.pagingEnabled = YES;

        [self addSubview:scrollView];

        _contentScrollView = scrollView;

}

创建UIPageControl

-(void)createPageControlView

{

       UIPageControl *pageControlVw = [[UIPageControl alloc] init];

      pageControlVw.frame = CGRectMake(0, 0, 80, 20);

      pageControlVw.center = CGPointMake(self.center.x, self.bounds.size.height - 20);

      pageControlVw.backgroundColor = [UIColor redColor];

      _pageControlView.pageIndicatorTintColor = [UIColor yellowColor];

      _pageControlView.currentPageIndicatorTintColor = [UIColor purpleColor];

      [self addSubview:pageControlVw];

      _pageControlView = pageControlVw;

}

//value对Count取模,并保证为正值

//这里很重要,是实现无限循环的重要的一步,比如现在显示的是第一张图片,_currentImgIndex=0,向左滑动后就显示_currentImgIndex+1张图片,可是_currentImgIndex+1可能回大于_imgUrlArr的数组count,这里取模,其次还要保证为正数,比如,如果向右边滑动是就显示_currentImgIndex-1张图片,_currentImgIndex-1取模也可能为负数,此时加上count保证为正数

-(NSInteger)switchToMValue:(NSInteger)value Count:(NSInteger)count

{

       NSInteger result = value % count;

       return result >=0 ? result : result + count;

}

重写imgUrlArr的set方法

-(void)setImgUrlArr:(NSArray *)imgUrlArr

{

        _imgUrlArr = [imgUrlArr copy];

        NSInteger count = imgUrlArr.count;

       if (count <= 0 )

       {

           return;

       }

      //如果只显示一张图片,那就没有旋转情况

      if (count == 1)

      {

             UIImageView *imgView = [[UIImageView alloc]init];

             imgView.frame = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height);

            [_contentScrollView addSubview:imgView];  

            _pageControlView.numberOfPages = 1; 

            _pageControlView.currentPage = 0;

           _contentScrollView.contentSize = CGSizeMake(self.bounds.size.width, self.bounds.size.height);

           NSURL *imgUrl = [NSURL URLWithString:imgUrlArr[0]];

          [imgView sd_setImageWithURL:imgUrl placeholderImage:nil];

          return;

      }

      if (count > 1)

      {

                 //这里只使用3个ImgView轮转多张图片,数量2,3,4,5,6...

                  for(int i = 0; i < 3 ;i++)

                  {

                         UIImageView *imgView = [[UIImageView alloc] init];

                          imgView.frame = CGRectMake(i * self.bounds.size.width, 0, self.bounds.size.width, self.bounds.size.height);

                          imgView.layer.masksToBounds = YES;

                          NSString *urlStr = urlStr = _imgUrlArr[[self switchToValue:i-1 Count:count]];

                          NSURL *imgUrl = [NSURL URLWithString:urlStr];

                           [imgView sd_setImageWithURL:imgUrl  placeholderImage:nil];

                           if (i == 0)

                            {

                                    _imgView1 = imgView; 

                             }

                             else if (i == 1)

                            {

                                   _imgView2 = imgView;

                           }

                           else if (i == 2)

                           {

                                 _imgView3 = imgView; 

                            }

                            [_contentScrollView addSubview:imgView];

                  }

                _pageControlView.numberOfPages = count; 

               _pageControlView.currentPage = 0;

               _contentScrollView.contentSize = CGSizeMake(self.bounds.size.width * 3,     self.bounds.size.height);

               _currentImgIndex = 0;

              [_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];

            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,  0),   ^{

                     //循环轮转图片

                     [self switchImg];

          });

     }

}

5秒旋转图片

-(void)switchImg

{

         while (1)

         {

                    [NSThread sleepForTimeInterval:WiatForSwitchImgMaxTime];

                    //如果正在拖拽图片,此次作废 

                     if (_isDragImgView) {

                              continue;

                      }

                       _currentPage = [self switchToValue:_currentPage + 1 Count:_imgUrlArr.count];

                       dispatch_async(dispatch_get_main_queue(), ^{

                                   _pageControlView.currentPage = _currentPage;

                                  _contentScrollView.contentOffset = CGPointMake(2 * self.bounds.size.width, 0);

                                  [self reSetImgUrlWithDirection:SwitchDirectionLeft];

                 });

         }

}

当手动旋转图片

-(void)switchImgByDirection:(SwitchDirection)direction

{

          if (direction == SwitchDirectionNone) {

                 return;

         }

         [self reSetImgUrlWithDirection:direction];

         [_contentScrollView setContentOffset:CGPointMake(self.bounds.size.width, 0) animated:NO];

}

旋转图片后重新调整3个UIImageView显示的内容,如实现思想所述

-(void)reSetImgUrlWithDirection:(SwitchDirection)direction

{

          if (direction == SwitchDirectionRight) {

                  [_imgView1 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex - 2 Count:_imgUrlArr.count]]] placeholderImage:nil];

                  [_imgView2 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex - 1 Count:_imgUrlArr.count]]] placeholderImage:nil];

                  [_imgView3 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex Count:_imgUrlArr.count]]] placeholderImage:nil];

                  _currentImgIndex = [self switchToValue:_currentImgIndex - 1 Count:_imgUrlArr.count];

           }

          else if(direction == SwitchDirectionLeft)

          {

                    [_imgView1 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex Count:_imgUrlArr.count]]] placeholderImage:nil];

                    [_imgView2 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex + 1 Count:_imgUrlArr.count]]] placeholderImage:nil];

                    [_imgView3 sd_setImageWithURL:[NSURL URLWithString:_imgUrlArr[[self switchToValue:_currentImgIndex + 2 Count:_imgUrlArr.count]]] placeholderImage:nil];

                    _currentImgIndex = [self switchToValue:_currentImgIndex + 1 Count:_imgUrlArr.count];

         }

}

实现UIScrollVie3个代理方法

#pragma mark -------------Delegate---------------

//记住滑动的方向

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

       static float newx = 0;

       static float oldx = 0;

      newx= scrollView.contentOffset.x ;

      if (newx != oldx )

      {

             if (newx > oldx)

             {

                     _swDirection = SwitchDirectionLeft;

             }else if(newx < oldx)

            {

                    _swDirection = SwitchDirectionRight;

            }

           oldx = newx;

      }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

        _isDragImgView = YES;

}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{

         //向左旋转

         if (_swDirection == SwitchDirectionLeft)

         {

                   _currentPage = [self switchToValue:_currentPage + 1 Count:_imgUrlArr.count];

          }//向右旋转

         else if (_swDirection == SwitchDirectionRight)

         {

                 _currentPage = [self switchToValue:_currentPage - 1 Count:_imgUrlArr.count];

         }

         _pageControlView.currentPage = _currentPage;

         if (_swDirection != SwitchDirectionNone) {

         [self switchImgByDirection:_swDirection];

         }

        _isDragImgView = NO;

}

以上为实现代码,现在看看怎么用,例如:

JGCirculateSwitchImgView *jView = [[JGCirculateSwitchImgView alloc] initWithFrame:CGRectMake(20,100, 280, 250)];

NSArray *imgUrlArr = @[@"http://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201119031647109.jpg",

@"http://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201116215754685.jpg",

@"http://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201115524758041.jpg",

@"http://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201114495822068.jpg",

@"http://www.blisscake.cn/Upload/Product/Show/Source/ps_1507201107522493367.jpg"];

jView.imgUrlArr = imgUrlArr;

[self.view addSubview:jView];

可以看到封装之后,代码的重用性很高,使用起来很简单,就这么4句代码就可以实现图片的无限循环轮转。

----------语言表达能力有待提高,我都写完了,不知道自己的表达的清楚不清楚。----------

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容