在iOS开发中,经常会在APP首页看到多张图片进行轮换。刚开始做的时候,感觉很麻烦,不是很好做,查阅资料后,我总结了一下,自己封装了一个简单的轮转图片库;

UIScrollView无限滑动 ,只需要三个View,左视图,中视图,右视图。无论向左滑动,还是向右滑动,都显示中间的一个View;

( _scrollView.contentOffset =CGPointMake(scrollView.bounds.size.width,0); )

//  CircleScrollView.h


#import <UIKit/UIKit.h>

#import "UIImageView+WebCache.h" // 当使用网络图片的时候,才会用到SDWebImage

@protocol CircleScrollViewDelegate <NSObject>

@optional

/**

 *  滚动图片总数

 *  @return 要滚动的图片的个数

 */

- (NSInteger) numberOfImagesInScrollView;

/**

 *  返回索引位置的图片,仅当滚动的为图片时使用

 *  @param index 索引位置

 *  @return 索引位置的图片

 */

-(UIImage *)imageForIndex:(NSInteger) index;

/**

 *  返回索引位置的图片URL,仅当滚动的为图片时使用

 *  @param index 索引位置

 *  @return 索引位置对应的图片URL

 */

-(NSURL *)imageURLForIndex:(NSInteger)index;

/**

 *  选中相应的视图的操作

 *  @param index 选中的相应的视图

 */

- (void)didSelectAtIndex:(NSInteger) index;

@end

@interface CircleScrollView :UIView <UIScrollViewDelegate>

@property (nonatomic,strong,readonly)UIScrollView *scrollView; 

@property (nonatomic,strong,readonly)UIPageControl *pageControl;

@property (nonatomic,strong,readonly)UIImageView *leftView;

@property (nonatomic,strong,readonly)UIImageView *middleView;

@property (nonatomic,strong,readonly)UIImageView *rightView;

@property (nonatomic,assign)int currentPageNo;

@property (nonatomic,assign,getter=isAutoLoop)BOOL autoLoop;//是否自动轮动

//@property (nonatomic,copy) NSArray *scrollImgs; 

@property (nonatomic,weak)id<CircleScrollViewDelegate> delegate;//代理

@end

//  CircleScrollView.m

#import "CircleScrollView.h"

@interfaceCircleScrollView ()

{

    NSTimer *_timer;

}

@end

@implementation CircleScrollView

/*

    自定义的ScrollView。功能如下:

    循环滑动

    使用分两步:

 (1)创建数据源(数据源中存放要滚动的图片)

 (2)_circleScrollView = [[CircleScrollView alloc] initWithFrame:CGRectMake(20, 20, 128, 128)];

 (3)设置代理 _circleScrollView.delegate = self;

 */

-(instancetype)initWithFrame:(CGRect)frame{

    self = [superinitWithFrame:frame];

    if (self) {

        _scrollView = [[UIScrollViewalloc]initWithFrame:self.bounds];

        _scrollView.delegate =self;

        _scrollView.showsHorizontalScrollIndicator =NO;

        _pageControl = [[UIPageControlalloc]initWithFrame:CGRectMake(0,self.frame.size.height-10,self.frame.size.width,10)];

        _pageControl.backgroundColor = [UIColorlightGrayColor];

        _pageControl.pageIndicatorTintColor = [UIColorredColor];

        _pageControl.currentPageIndicatorTintColor = [UIColorblueColor];

        _pageControl.alpha =0.5;

        _leftView = [[UIImageViewalloc]initWithFrame:CGRectMake(self.frame.size.width*0,0,self.frame.size.width,self.frame.size.height)];

        _middleView = [[UIImageViewalloc]initWithFrame:CGRectMake(self.frame.size.width*1,0,self.frame.size.width,self.frame.size.height)];

        _rightView = [[UIImageViewalloc]initWithFrame:CGRectMake(self.frame.size.width*2,0,self.frame.size.width,self.frame.size.height)];

        [_scrollViewaddSubview:_leftView];

        [_scrollViewaddSubview:_middleView];

        [_scrollViewaddSubview:_rightView];

        _scrollView.pagingEnabled =YES;

        _scrollView.contentSize =CGSizeMake(self.frame.size.width*3,self.frame.size.height);

        _scrollView.contentOffset =CGPointMake(self.frame.size.width,0);

        [selfaddSubview:_scrollView];

        [selfaddSubview:_pageControl];

    }

    returnself;

}

-(void)setDelegate:(id<CircleScrollViewDelegate>)delegate

{

//    NSLog(@"设置代理");

    _delegate = delegate;

    if ([_delegaterespondsToSelector:@selector(numberOfImagesInScrollView)]) {

        NSInteger number = [_delegatenumberOfImagesInScrollView];

        _pageControl.numberOfPages = number;

        _pageControl.currentPage =0;

        _currentPageNo =0;

//        _leftView.image = [_delegate imageForIndex:number-1];

//        _middleView.image = [_delegate imageForIndex:_currentPageNo];

        int nextNo =_currentPageNo;

        if (number >2) {

            nextNo = _currentPageNo+1;

        }

//        _rightView.image = [_delegate imageForIndex:nextNo];

        if ([self.delegaterespondsToSelector:@selector(imageURLForIndex:)]) {

            [_leftViewsd_setImageWithURL:[_delegateimageURLForIndex:number-1]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

                //            NSLog(@"");

            }];

            [_middleViewsd_setImageWithURL:[_delegateimageURLForIndex:_currentPageNo]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

            }];

            [_rightViewsd_setImageWithURL:[_delegateimageURLForIndex:nextNo]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

            }];

        } elseif ([self.delegaterespondsToSelector:@selector(imageForIndex:)]){

            _leftView.image = [_delegateimageForIndex:number-1];

            _middleView.image = [_delegateimageForIndex:_currentPageNo];

            _rightView.image = [_delegateimageForIndex:nextNo];

        }

    }

    if ([_delegaterespondsToSelector:@selector(didSelectAtIndex:)]) {

        _middleView.userInteractionEnabled =YES;

        UITapGestureRecognizer *tap = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(selectAction:)];

        [_middleViewaddGestureRecognizer:tap];

    }

}

-(void)selectAction:(UITapGestureRecognizer *)gesture {

    if ([self.delegaterespondsToSelector:@selector(didSelectAtIndex:)]) {

        [self.delegatedidSelectAtIndex:_currentPageNo];

    }

}

-(void)autoLoop{

    _currentPageNo++;

    //自动循环

    [_scrollViewscrollRectToVisible:CGRectMake(_scrollView.bounds.size.width*2,0,_scrollView.bounds.size.width,_scrollView.bounds.size.height)animated:YES];

}

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

//    NSLog(@"scrollViewDidEndDecelerating");

    int pageNo = scrollView.contentOffset.x/scrollView.bounds.size.width;

    long imgCount = [_delegatenumberOfImagesInScrollView];

//    NSLog(@"pageNo : %i",pageNo);

    if (pageNo ==0) {

        _currentPageNo--;

    } elseif (pageNo ==2){

        _currentPageNo++;

    }

    if (_currentPageNo <0) {

        _currentPageNo = (int)(imgCount -1);

    } elseif (_currentPageNo > imgCount -1) {

        _currentPageNo =0;

    }

    int previousPage =_currentPageNo -1;

    if (previousPage <0) {

        previousPage = (int)(imgCount -1);

    }

    int nextPage =_currentPageNo +1;

    if (nextPage > imgCount-1) {

        nextPage = 0;

    }

    _pageControl.currentPage =_currentPageNo;

    if ([self.delegaterespondsToSelector:@selector(imageURLForIndex:)]) {

        [_leftViewsd_setImageWithURL:[_delegateimageURLForIndex:previousPage]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

        }];

        [_middleViewsd_setImageWithURL:[_delegateimageURLForIndex:_currentPageNo]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

        }];

        [_rightViewsd_setImageWithURL:[_delegateimageURLForIndex:nextPage]placeholderImage:[UIImagenew]completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType,NSURL *imageURL) {

        }];

    } elseif ([self.delegaterespondsToSelector:@selector(imageForIndex:)]){

        _leftView.image = [_delegateimageForIndex:previousPage];

        _middleView.image = [_delegateimageForIndex:_currentPageNo];

        _rightView.image = [_delegateimageForIndex:nextPage];

    }

    _scrollView.contentOffset =CGPointMake(scrollView.bounds.size.width,0);

}

@end

  关于自动循环,我们可以自定义,其实就是加一个NSTimer定时器,每过一定的时间让scrollView滑向下一个View,即:

[_scrollViewscrollRectToVisible:CGRectMake(_scrollView.bounds.size.width*2,0,_scrollView.bounds.size.width,_scrollView.bounds.size.height)animated:YES];
scrollView会自动的滑向第三个View。然后图片就可以自动定时滑动了。 使用上述自定义的轮转图片时,一定要遵守UIScrollViewDelegate协议并实现代理方法,否则不可用。

UIScrollView之轮转图片的更多相关文章

  1. 常错-UIScrollView中得图片不能被拖动

    经常在开发中,发现自己UIScrollView里面的图片不能被拖动 在这里做个备忘,第一种可能是contentSize没有设置,第二种可能是contentSize设置的太小了. 测试后发现,与user ...

  2. iOS下uiview和uiscrollview设置背景图片的源码

    1.uiscrollview 设置背景图片 // Setup the Scroll ViewUIScrollView*tempScrollView=(UIScrollView*)self.view;t ...

  3. UIScrollView浏览一组图片,且图片与图片之间有间隔

    ---恢复内容开始--- UIScrollView是可以浏览一组view的,只要将其属性 pagingEnabled设置为true就可以了.具体过程是这样的, 1:将一组图片按照从左到右的顺序添加到U ...

  4. 【iOS开发-54】案例学习:通过UIScrollView的缩放图片功能练习代理模式的详细实现

    案例:(在模拟器中按住option键,点击鼠标就会出现缩放的手势) (1)在ViewController.m中: --缩放东西是UIScrollView除了滚动之外的还有一个功能,所以须要缩放的东西应 ...

  5. UIScrollView做循环图片

    #import "ViewController.h" #define IMAGE_COUNT 6 @interface ViewController () { UIImageVie ...

  6. iOS:UIScrollView控件和UIPageControl控件的详解

    UIScrollView滚动视图控件和UIPageControl分页视图控件:    UIScrollView用于显示多于一个屏幕的内容,超出屏幕范围的内容可以通过滑动进行查看,当然UIPagecon ...

  7. iOS开发——UI基础-UIScrollView

    一.UIScrollView使用的步骤 1.创建UIScrollView 2.将需要展示的内容添加到UIScrollView中 3.设置UIScrollView的滚动范围 (contentSize) ...

  8. iOS开发-UITableView顶部图片下拉放大

    关于顶部图片下拉放大,在用户展示的个人中心显示用户个人头像信息,设置UITableView的headerView实现,UITableView继承自UIScrollView,同样的设置UIScrollV ...

  9. ScrollView图片分页显示-简单

    用到的控件: 1>UIScrollView:宽度和图片的宽度一样,因为分页的代码就一句 // 设置分页,这个分页的原理实际上是按照ScrollView的宽进行分页的,这里的图片的宽由于和Scro ...

随机推荐

  1. java中的hashcode()和equals()

    equals()和hashcode()都继承自object类. equals() equals()方法在object类中定义如下: public boolean equals(Object obj) ...

  2. ASP.NET MVC Model绑定小结

    Model绑定是指从URL提取数据,生成对应Action方法的参数这个过程.前面介绍的一系列Descriptor负责提供了控制器,行为方法和参数的元数据,ValueProvieder负责获取数据,剩下 ...

  3. 【C#】妈妈再也不用担心自定义控件如何给特殊类型的属性添加默认值了,附自定义GroupBox一枚

    ------------------更新:201411190903------------------ 经过思考和实践,发现套路中的第1条是不必要的,就是完全可以不用定义一个名为Default+属性名 ...

  4. 动易CMS之标签管理

    一.如何添加一个标签 1.系统设置->模板标签管理->添加标签 2.输入标签名称,根据需要选择数据设置: sql语句则选择[系统数据库SQL查询] 3.添加参数 4.系统可以根据设置的条件 ...

  5. Ext.grid.Panel表格分页存储过程

    /*首先需要引入两个Extjs插件类 Ext.ux.data.PagingMemoryProxy和Ext.ux.ProgressBarPager这两个类*/ /*下面是控制弹出窗体放大缩小时窗体居中的 ...

  6. Scalaz(18)- Monad: ReaderWriterState-可以是一种简单的编程语言

    说道FP,我们马上会联想到Monad.我们说过Monad的代表函数flatMap可以把两个运算F[A],F[B]连续起来,这样就可以从程序的意义上形成一种串型的流程(workflow).更直白的讲法是 ...

  7. Lock的实现之ReentrantLock详解

    摘要 Lock在硬件层面依赖CPU指令,完全由Java代码完成,底层利用LockSupport类和Unsafe类进行操作: 虽然锁有很多实现,但是都依赖AbstractQueuedSynchroniz ...

  8. log4j在javaWeb项目中的使用

    在前边的文章中对log4j的配置文件进行了说明,今天介绍如何在普通的javaWeb项目中使用log4j. 在日常的开发过程中,日志使用的很频繁,我们可以利用日志来跟踪程序的错误,程序运行时的输出参数等 ...

  9. Java的对象初始化过程

    成员变量(字段)初始化顺序 在一个类里初始化的顺序是由成员变量在类里面的定义的顺序来决定的.即使成员变量大量散布于类的各个方法定义的中间,那些成员变量仍会在调用任何方法之前得以初始化,甚至在构造函数调 ...

  10. 使用快捷键提升C#开发效率

    好的工具能帮我们提升开发效率,能用工具去做的事情尽量使用工具,让我们的开发尽量自动化是提升开发效率的关键因素. 很多人都用过Resharper,也被Resharper超多的快捷键所折服,本篇文章我总结 ...