[iOS][Objective-C]:用UIScrollView实现的图片轮播器

现在的App中,图片轮播器是再常见的不过的一种UI交互方式了。今天这边就给大家写一个用scrollview完成的图片轮播器。

先来看下效果:

《[iOS][Objective-C]:用UIScrollView实现的图片轮播器》

其实即使是IOS的初学者,让图片滚动起来并不是难题,而这边图片轮播的难点在于一个图片周期的循环,也就是在最后一张跳入第一张的(或者最后一张跳入第一张)时的动画问题。

以下提供实现思路:

页面上只需要一个scrollView,在ScrollView上添置左中右各三个UIImageVIew

《[iOS][Objective-C]:用UIScrollView实现的图片轮播器》 1

当图片停止时,此时左中右图片分别为 图1 图2 图3,

当前scrollView的始终停留在Center ImageView上。

当向右滑动时,scrollView最终停留在RightImageView(即图2)上时,

在- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView方法中

刷新三个ImageView的图片,此时左中右三张图片分别为图2 图3 图4

同时将scrollView移动回中间Center;

注意:刷新三个ImageView和scrollView的操作是同时进行的。并且scrollView移动的过程中 用到- (void)setContentOffset:(CGPoint)contentOffset animated:(BOOL)animated;方法时,需要将动画效果设置为NO;

此时在用户看来,就是手机屏幕中从图1过渡到图2的动画过程。

代码:

– (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {

 [self reloadImageViews];

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

}

– (void)reloadImageViews {

          CGPointscrollViewOffset = [_mainScrollViewcontentOffset];

          if(scrollViewOffset.x==2*_mainScrollView.bounds.size.width) {

          [selfcurrentImageIndexAdd];

    }elseif(scrollViewOffset.x==0) {

         [selfcurrentImageIndexMinus];

    }

 _centerImageView.image=               [UIImageimageNamed:_picDataArray[self.currentImageIndex]];

_leftImageView.image= [UIImageimageNamed:_picDataArray[self.leftImageIndex]];

_rightImageView.image =[UIImageimageNamed:_picDataArray[self.rightImageIndex]];

}

对应这个案列,我使用了3个全局变量Index来记录三张ImageView的图片

@property(nonatomic,assign)NSUIntegercurrentImageIndex;

@property(nonatomic,assign)NSIntegerleftImageIndex;

@property(nonatomic,assign)NSIntegerrightImageIndex;

刚才提到的最后一张图和第一张图的动画,可以在Index上的判断来实现

– (NSInteger)leftImageIndex {

     if(_currentImageIndex==0) {

           _leftImageIndex=kImageCount-1;

      }else{

           _leftImageIndex=_currentImageIndex-1;

  }

     return_leftImageIndex;

}

– (NSInteger)rightImageIndex {

         if(_currentImageIndex==kImageCount-1) {

            _rightImageIndex=0;

          }else{

            _rightImageIndex=_currentImageIndex+1;

          }

       return_rightImageIndex;

}

– (void)currentImageIndexAdd {

         if(self.currentImageIndex==kImageCount-1) {

                 self.currentImageIndex=0;

          }else{

                  self.currentImageIndex=self.currentImageIndex+1;

          }

    }

– (void)currentImageIndexMinus {

         if(self.currentImageIndex==0) {

                self.currentImageIndex=kImageCount-1;

          }else{

                self.currentImageIndex=self.currentImageIndex-1;

         }

}

最后加上了一些简单的封装和定时器效果

附上GitHub链接:GitHub – DerrickQin2853/SimplePictureCarouselScrollView: A Demo PictureCarousel using scrollView

如有问题,欢迎各位指出讨论。感谢阅读

    原文作者:DerrickQin
    原文地址: https://www.jianshu.com/p/c8620d5301dc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞