欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS实现无限循环图片轮播器的封装

程序员文章站 2023-12-03 14:24:52
 项目中很多时候会碰到这个需求,实现多张图片的无限循环轮转,以前做过,项目中几个地方的都用到了,当时没有封装,几个地方都拷贝几乎一样的代码,代码复用性不好,今天没...

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

  首先,说说我实现循环轮转图片的思想,在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句代码就可以实现图片的无限循环轮转。

以上就是本文的全部内容,希望对大家的学习有所帮助。