iOS轮播图的封装库(一行代码解决应用中的scrollView轮播)

96
D了个Y
0.2 2016.05.23 10:54* 字数 392

作为一个iOS开发者,我们经常需要用到轮播图,比如:我们首页顶部的广告轮播,商品详情页面的商品图片轮播等,如果我们每个地方都去直接定义scrollView,然后设置定时器等等操作,就会觉得很繁琐....于是就想着封装一个轮播图库FFScrollView
老惯例哈,先给出gitHub上的代码地址哈:
https://github.com/BrightMoment/FFScrollView
1.首先看下FFScrollView.h中的代码

#import <UIKit/UIKit.h>
typedef enum
{
    FFScrollViewSelecttionTypeTap = 100,  //默认的为可点击模式
    FFScrollViewSelecttionTypeNone   //不可点击的
}FFScrollViewSelecttionType;

@protocol FFScrollViewDelegate <NSObject>

@optional
- (void)scrollViewDidClickedAtPage:(NSInteger)pageNumber;

@end

@interface FFScrollView : UIView <UIScrollViewDelegate>
{
    NSTimer *timer;
    NSArray *sourceArr;
    
    NSString * tagStr;
    
    UILabel * lable1;
    UILabel * lable2;
    UILabel * lable3;
}
@property(strong,nonatomic) UIScrollView *scrollView;
@property(strong,nonatomic) UIPageControl *pageControl;
@property(assign,nonatomic) FFScrollViewSelecttionType selectionType;
@property(assign,nonatomic) id <FFScrollViewDelegate> pageViewDelegate;
- (id)initPageViewWithFrame:(CGRect)frame views:(NSArray *)views tag:(NSString *)tag;
@end

上面代码主要看下这部分

typedef enum
{
    FFScrollViewSelecttionTypeTap = 100,  //默认的为可点击模式
    FFScrollViewSelecttionTypeNone   //不可点击的
}FFScrollViewSelecttionType;

@protocol FFScrollViewDelegate <NSObject>

@optional
- (void)scrollViewDidClickedAtPage:(NSInteger)pageNumber;

@end

我们程序中常用的轮播图大致分为2种,一种是可以点击跳转到其他页面的;一种是只用于展示的....所以这边我们枚举了2种类型
还有一个代理FFScrollViewDelegate,主要是用来处理点击后的事件的
2.下面我们来看看FFScrollView.m文件

#import "FFScrollView.h"

@implementation FFScrollView
@synthesize scrollView;
@synthesize pageControl;
@synthesize selectionType;
@synthesize pageViewDelegate;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
    }
    return self;
}

#pragma mark-- init methods
- (id)initPageViewWithFrame:(CGRect)frame views:(NSArray *)views tag:(NSString *)tag
{
    self = [super initWithFrame:frame];
    if (self) {
        selectionType = FFScrollViewSelecttionTypeTap;
        sourceArr = views;
        tagStr=tag;
        self.userInteractionEnabled = YES;
        [self iniSubviewsWithFrame:frame];
    }
    return self;
}

-(void)iniSubviewsWithFrame:(CGRect)frame
{
    CGFloat width = frame.size.width;
    CGFloat height = frame.size.height;
    CGRect fitRect = CGRectMake(0, 0, width, height);
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:fitRect];
    self.scrollView.pagingEnabled = YES;
    self.scrollView.delegate = self;
    self.scrollView.contentSize = CGSizeMake(width*(sourceArr.count+2), height);
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    [self addSubview:self.scrollView];
    
    
    
    UIImageView *firstImageView = [[UIImageView alloc]initWithFrame:fitRect];
    
    [firstImageView sd_setImageWithURL:[NSURL URLWithString:[sourceArr lastObject]] placeholderImage:defaultImage640];

    [self.scrollView addSubview:firstImageView];
    
 
    
    lable2 =[[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-80, self.frame.size.height-30, 80, 20)];
    lable2.font=[UIFont systemFontOfSize:18.0f];
    lable2.textColor=[UIColor whiteColor];
    lable2.textAlignment=1;
//    if([tagStr isEqualToString:@"home"])
//    {
//        [self addSubview:lable2];
//    }
   
    lable2.text=[NSString stringWithFormat:@"%zi/%zi",1,sourceArr.count];

    
    for (int i = 0; i < sourceArr.count; i++) {
        UIImageView *imageview = [[UIImageView alloc]initWithFrame:CGRectMake(width*(i+1), 0, width, height)];
        
        [imageview sd_setImageWithURL:[NSURL URLWithString:[sourceArr objectAtIndex:i]] placeholderImage:defaultImage640];

        [self.scrollView addSubview:imageview];
        
      
        
    }
    
    UIImageView *lastImageView = [[UIImageView alloc]initWithFrame:CGRectMake(width*(sourceArr.count+1), 0, width, height)];
    [lastImageView sd_setImageWithURL:[NSURL URLWithString:[sourceArr objectAtIndex:0]] placeholderImage:defaultImage640];

    [self.scrollView addSubview:lastImageView];
    
    
  
    
    lable3.text=[NSString stringWithFormat:@"%zi/%zi",1,sourceArr.count];

    self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, height-30, width, 30)];
    self.pageControl.numberOfPages = sourceArr.count;
    self.pageControl.currentPage = 0;
    self.pageControl.enabled = YES;
   // [self addSubview:self.pageControl];
    
    [self.scrollView scrollRectToVisible:CGRectMake(width, 0, width, height) animated:NO];
    timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage:) userInfo:nil repeats:YES];
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    singleTap.numberOfTapsRequired = 1;
    [self addGestureRecognizer:singleTap];
    
    
  
    

}

#pragma mark --- custom methods
//自动滚动到下一页
-(IBAction)nextPage:(id)sender
{
    
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int currentPage = self.scrollView.contentOffset.x/pageWidth;
    if (currentPage == 0) {
        self.pageControl.currentPage = sourceArr.count-1;
        
        
    }
    else if (currentPage == sourceArr.count+1) {
        self.pageControl.currentPage = 0;
        

    }
    else {
        self.pageControl.currentPage = currentPage-1;
        


        
    }
    NSInteger currPageNumber = self.pageControl.currentPage;
    CGSize viewSize = self.scrollView.frame.size;
    CGRect rect = CGRectMake((currPageNumber+2)*pageWidth, 0, viewSize.width, viewSize.height);
    [self.scrollView scrollRectToVisible:rect animated:YES];
    currPageNumber++;
    if (currPageNumber == sourceArr.count) {
        CGRect newRect=CGRectMake(viewSize.width, 0, viewSize.width, viewSize.height);
        [self.scrollView scrollRectToVisible:newRect animated:NO];
        currPageNumber = 0;
    }
    self.pageControl.currentPage = currPageNumber;
    lable2.text=[NSString stringWithFormat:@"%zi/%zi",currPageNumber+1,sourceArr.count];

}

//点击图片的时候 触发
- (void)singleTap:(UITapGestureRecognizer *)tapGesture
{
    if (selectionType != FFScrollViewSelecttionTypeTap) {
        return;
    }
    if (pageViewDelegate && [pageViewDelegate respondsToSelector:@selector(scrollViewDidClickedAtPage:)]) {
        [pageViewDelegate scrollViewDidClickedAtPage:self.pageControl.currentPage];
    }
}

#pragma mark---- UIScrollView delegate methods
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //开始拖动scrollview的时候 停止计时器控制的跳转
    [timer invalidate];
    timer = nil;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    CGFloat width = self.scrollView.frame.size.width;
    CGFloat heigth = self.scrollView.frame.size.height;
    //当手指滑动scrollview,而scrollview减速停止的时候 开始计算当前的图片的位置
    int currentPage = self.scrollView.contentOffset.x/width;
    if (currentPage == 0) {
        [self.scrollView scrollRectToVisible:CGRectMake(width*sourceArr.count, 0, width, heigth) animated:NO];
        self.pageControl.currentPage = sourceArr.count-1;
    }
    else if (currentPage == sourceArr.count+1) {
        [self.scrollView scrollRectToVisible:CGRectMake(width, 0, width, heigth) animated:NO];
        self.pageControl.currentPage = 0;
    }
    else {
        self.pageControl.currentPage = currentPage-1;
    }
    //拖动完毕的时候 重新开始计时器控制跳转
    timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(nextPage:) userInfo:nil repeats:YES];
}

上面的initPageViewWithFrame方法是我们创建这样一个轮播控件的初始化方法....
下面的代码是我们点击轮播图时的点击事件,并用代理的方式传给我们的代理对象...我们在代理对象中实现这个方法就可以了

//点击图片的时候 触发
- (void)singleTap:(UITapGestureRecognizer *)tapGesture
{
    if (selectionType != FFScrollViewSelecttionTypeTap) {
        return;
    }
    if (pageViewDelegate && [pageViewDelegate respondsToSelector:@selector(scrollViewDidClickedAtPage:)]) {
        [pageViewDelegate scrollViewDidClickedAtPage:self.pageControl.currentPage];
    }
}

3.我们具体看下这个控件的使用方法

- (id)initPageViewWithFrame:(CGRect)frame views:(NSArray *)views tag:(NSString *)tag

其中views这个参数我们可以传入图片的链接地址(如果图片来自于网络);自然也可以传入图片的名称
先给出创建FFScrollView的代码片段()

首先遵守这个协议@interface HomeViewController : CommonViewController<FFScrollViewDelegate>
然后
//在某个ViewController的.m文件中
-(void)addTopBanner:(NSArray *)array
{
    FFScrollView *ffScroll=[[FFScrollView alloc]initPageViewWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150) views:array tag:@"home"];
    ffScroll.pageViewDelegate=self;
    [scr addSubview:ffScroll];
}

#pragma mark - FFScrollViewDelegate
-(void)scrollViewDidClickedAtPage:(NSInteger)pageNumber
{
  //根据点击的图片索引pageNumber,来编写具体的点击事件
}

更详细的介绍,去查看我gitHub上的代码吧
https://github.com/BrightMoment/FFScrollView

iOS开发点滴记录
Web note ad 1