iOS轮播图

来源:互联网 发布:软件开发费用 税率 编辑:程序博客网 时间:2024/05/06 12:59

该demo中,加载网络图片采用第三方库SDWebImage

(使用时拷贝下面的代码即可)

1、新建一个继承UIView的类:JJRollBanner


JJRollBanner.h头文件中的代码:

#import <UIKit/UIKit.h>

#import "UIImageView+WebCache.h"


@class JJRollBanner;

@protocol JJRollBannerDelegate <NSObject>


/**

 *  选择图片

 *

 *  @param index 图片image Viewtag

 */

-(void)didSelectImage:(NSInteger)index;


@end


@interface JJRollBanner : UIView


-(instancetype)initWithFrame:(CGRect)frame;


/************************************************************/

/******** durationTimer, currentPageColor, pageColor ********/

/********    在调用这些参数的时候最好在添加图片数组之前     ********/

/************************************************************/


/**

 *  定时器执行的时间

 *  默认是 3.0

 */

@property (assign,nonatomic) CGFloat durationTimer;


/**

 *  当前点的颜色

 *  默认 -- 红色

 */

@property (strong,nonatomic) UIColor *currentPageColor;

/**

 *  点的背景颜色

 *  默认-- 亮灰色

 */

@property (strong,nonatomic) UIColor *pageColor;


/**

 *  加载本地图片

 */

@property (strong,nonatomic) NSArray *loactionImageArray;

/**

 *  加载网路图片

 */

@property (strong,nonatomic) NSArray *lineImageArray;

/**

 *  代理

 */

@property (weak, nonatomic) id<JJRollBannerDelegate> delegate;


/**

 *  更新的时候调用

 *

 *  @param array 本地图片数组

 */

-(void)refreshRollWithLocationArray:(NSArray*)loactionImageArray;


/**

 *  更新的时候调用

 *

 *  @param array 网络图片数组

 */

-(void)refreshRollWithNetworkArray:(NSArray *)lineImageArray;


@end



JJRollBanner.m文件中实现方法代码:


#import "JJRollBanner.h"


@interface JJRollBanner ()<UIScrollViewDelegate>

/**

 *  滚动视图

 */

@property (strong,nonatomic) UIScrollView *bannerScrollView;

/**

 * 

 */

@property (strong,nonatomic) UIPageControl *pageView;

/**

 *  定时器

 */

@property (strong,nonatomic) NSTimer *timer;

/**

 *  纪录图片数组的个数

 */

@property (assign,nonatomic) NSInteger count;


@end


@implementation JJRollBanner



/**

 *  轮播滚动图片的实现方法

 *  

 *  1、实际上scrollerView上的图片的数量要比实际图片多俩张(第一张和最后一张)

 *  2、将最后一张图片放在scrollerViewcontentOffSet的第二个位置,第一张图片放到最后+1的位置

 *  

 *  假如有6张图片 ABCDEF

 *  那么排列方式 FABCDEFA

 *  

 *  scrollview显示的起始位置是contentOffSet.x = CGPoint(width, 0);widthscrollview的宽度

 *

 *  实现方式

 *  当从左往右滑到达最后A的时候跳到左边的A的位置

 *

 *

 *

 *  当从右往左滑到达最后F的时候跳到右边的F的位置

 */


/*

// Only override drawRect: if you perform custom drawing.

// An empty implementation adversely affects performance during animation.

- (void)drawRect:(CGRect)rect {

    // Drawing code

}

*/



-(instancetype)initWithFrame:(CGRect)frame

{

     self = [superinitWithFrame:frame];

    

    if (self) {

        

        /**

         *  初始化scrollview

         */

        [selfinitScrollView];

        

        /**

         *  初始化pagecontrol

         */

        [selfinitPageControl];

    }

    return self;

}


-(void)initScrollView

{

    self.bannerScrollView = [[UIScrollViewalloc] initWithFrame:CGRectMake(0,0, self.frame.size.width,self.frame.size.height)];

    self.bannerScrollView.showsHorizontalScrollIndicator = NO;

    self.bannerScrollView.showsVerticalScrollIndicator = NO;

    self.bannerScrollView.pagingEnabled =YES;

    self.bannerScrollView.scrollEnabled =YES;

    self.bannerScrollView.delegate =self;

    [selfaddSubview:self.bannerScrollView];

}


-(void)initPageControl

{

    float width = self.bannerScrollView.frame.size.width;

    float page_width = 160;

    float height = self.bannerScrollView.frame.size.height;

    

    self.pageView = [[UIPageControlalloc] initWithFrame:CGRectMake((width - page_width) /2, height - 20, page_width,20)];

    /**

     *  当前点的颜色

     */

    if(self.currentPageColor ==nil) {

        self.pageView.currentPageIndicatorTintColor = [UIColor redColor];

    }else{

        self.pageView.currentPageIndicatorTintColor =self.currentPageColor;

    }

    /**

     *  所有点的背景颜色

     */

    if (self.pageColor ==nil) {

        self.pageView.pageIndicatorTintColor = [UIColorlightGrayColor];

    }else{

        self.pageView.pageIndicatorTintColor =self.pageColor;

    }

    

    [self addSubview:self.pageView];

}


/**

 *  加载本地图片

 *

 *  @param loactionImageArray 本地图片名称

 */

-(void)setLoactionImageArray:(NSArray *)loactionImageArray

{

    _loactionImageArray = loactionImageArray;

    /**

     *  图片的数量

     */

    self.count = loactionImageArray.count;

    /**

     *  图片的宽高

     */

    CGFloat placeWidth = self.frame.size.width;

    CGFloat placeHeight = self.frame.size.height;

    

    /**

     *  图片填充

     */

    for(NSInteger index =0; index < self.count; index++)

    {

        UIImageView *imageView = [[UIImageViewalloc] initWithFrame:CGRectMake((index +1) * placeWidth, 0, placeWidth, placeHeight)];

        imageView.tag = 100 + index;

        imageView.image = [UIImageimageNamed:loactionImageArray[index]];

        /**

         *  铺满

         */

        imageView.layer.masksToBounds =YES;

        imageView.contentMode =UIViewContentModeScaleAspectFill;

        imageView.userInteractionEnabled = YES;

        

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

        [imageView addGestureRecognizer:tap];

        

        [self.bannerScrollViewaddSubview:imageView];

    }

    

    UIImageView *firstImage = [[UIImageViewalloc] initWithFrame:CGRectMake(0,0, placeWidth, placeHeight)];

    firstImage.tag = self.count + 100;

    firstImage.image = [UIImageimageNamed:[loactionImageArray lastObject]];

    firstImage.userInteractionEnabled =YES;

    /**

     *  铺满

     */

    firstImage.layer.masksToBounds =YES;

    firstImage.contentMode =UIViewContentModeScaleAspectFill;

    

    

    UITapGestureRecognizer *tap_first = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(chooseImage:)];

    [firstImage addGestureRecognizer:tap_first];

    [self.bannerScrollViewaddSubview:firstImage];

    

    UIImageView *lastImage = [[UIImageViewalloc] initWithFrame:CGRectMake((self.count +1) * placeWidth, 0, placeWidth, placeHeight)];

    lastImage.tag = 100;

    lastImage.image = [UIImageimageNamed:[loactionImageArray firstObject]];

    lastImage.userInteractionEnabled =YES;

    /**

     *  铺满

     */

    lastImage.layer.masksToBounds =YES;

    lastImage.contentMode =UIViewContentModeScaleAspectFill;

    

    UITapGestureRecognizer *tap_last = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(chooseImage:)];

    [firstImage addGestureRecognizer:tap_last];

    [self.bannerScrollViewaddSubview:lastImage];

    

    self.bannerScrollView.contentOffset =CGPointMake(placeWidth, 0);

    self.bannerScrollView.contentSize =CGSizeMake((self.count +2) * placeWidth, placeHeight);

    

    self.pageView.numberOfPages =self.count;

    self.pageView.currentPage =0;

    

    if(self.pageColor !=nil || self.currentPageColor !=nil)

    {

        [selffillPageColor];

    }

    

    [selfcreateTimer];

}


/**

 *  加载网络图片

 *

 *  @param lineImageArray 图片链接数组

 */

-(void)setLineImageArray:(NSArray *)lineImageArray

{


    _lineImageArray = lineImageArray;

    

    self.count = lineImageArray.count;

    

    CGFloat placeWidth = self.frame.size.width;

    CGFloat placeHeight = self.frame.size.height;

    

    /**

     *  图片填充

     */

    for(NSInteger index =0; index < self.count; index++)

    {

        UIImageView *imageView = [[UIImageViewalloc] initWithFrame:CGRectMake((index +1) * placeWidth, 0, placeWidth, placeHeight)];

        imageView.tag = 100 + index;

        [imageView sd_setImageWithURL:[NSURLURLWithString:lineImageArray[index]] placeholderImage:[UIImage imageNamed:@"img_01.jpg"] completed:nil];

        /**

         *  铺满

         */

        imageView.layer.masksToBounds =YES;

        imageView.contentMode =UIViewContentModeScaleAspectFill;

        imageView.userInteractionEnabled = YES;

        

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

        [imageView addGestureRecognizer:tap];

        

        [self.bannerScrollViewaddSubview:imageView];

    }

    

    UIImageView *firstImage = [[UIImageViewalloc] initWithFrame:CGRectMake(0,0, placeWidth, placeHeight)];

    firstImage.tag = self.count + 100;

    [firstImage sd_setImageWithURL:[NSURLURLWithString:[lineImageArray lastObject]] placeholderImage:[UIImageimageNamed:@"img_01.jpg"]completed:nil];

    /**

     *  铺满

     */

    firstImage.layer.masksToBounds =YES;

    firstImage.contentMode =UIViewContentModeScaleAspectFill;

    firstImage.userInteractionEnabled =YES;

    

    UITapGestureRecognizer *tap_first = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(chooseImage:)];

    [firstImage addGestureRecognizer:tap_first];

    [self.bannerScrollViewaddSubview:firstImage];

    

    UIImageView *lastImage = [[UIImageViewalloc] initWithFrame:CGRectMake((self.count +1) * placeWidth, 0, placeWidth, placeHeight)];

    lastImage.tag = 100;

    [lastImage sd_setImageWithURL:[NSURLURLWithString:[lineImageArray firstObject]] placeholderImage:[UIImageimageNamed:@"img_01.jpg"]completed:nil];

    /**

     *  铺满

     */

    lastImage.layer.masksToBounds =YES;

    lastImage.contentMode =UIViewContentModeScaleAspectFill;

    lastImage.userInteractionEnabled =YES;

    

    UITapGestureRecognizer *tap_last = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(chooseImage:)];

    [firstImage addGestureRecognizer:tap_last];

    [self.bannerScrollViewaddSubview:lastImage];

    

    self.bannerScrollView.contentOffset =CGPointMake(placeWidth, 0);

    self.bannerScrollView.contentSize =CGSizeMake((self.count +2) * placeWidth, placeHeight);

    

    self.pageView.numberOfPages =self.count;

    self.pageView.currentPage =0;

    

    if(self.pageColor !=nil || self.currentPageColor !=nil)

    {

        [selffillPageColor];

    }

    

    [selfcreateTimer];


}


/**

 *  填充pagecontrol的颜色

 */

-(void)fillPageColor

{

    /**

     *  当前点的颜色

     */

    if(self.currentPageColor ==nil) {

        self.pageView.currentPageIndicatorTintColor = [UIColor redColor];

    }else{

        self.pageView.currentPageIndicatorTintColor =self.currentPageColor;

    }

    /**

     *  所有点的背景颜色

     */

    if (self.pageColor ==nil) {

        self.pageView.pageIndicatorTintColor = [UIColorlightGrayColor];

    }else{

        self.pageView.pageIndicatorTintColor =self.pageColor;

    }

}


/**

 *  更新本地图片

 *

 *  @param loactionImageArray 本地图片数组

 */

-(void)refreshRollWithLocationArray:(NSArray *)loactionImageArray

{

    /**

     *  更新之前先把之前的定时器给关掉

     */

    [selfpauseTimer];

    /**

     *  调用加载本地图片的方法

     */

    [self setLoactionImageArray:loactionImageArray];

}


/**

 *  更新网络图片

 *

 *  @param loactionImageArray 网络图片数组

 */


-(void)refreshRollWithNetworkArray:(NSArray *)lineImageArray

{

    /**

     *  更新之前先把之前的定时器给关掉

     */

    [selfpauseTimer];

    /**

     *  调用加载网路图片的方法

     */

    [self setLineImageArray:lineImageArray];

}


/**

 *  滚动定时器的添加

 */

-(void)createTimer

{

    if(!self.durationTimer)

    {

        self.durationTimer =3.0f;

    }

    

    self.timer = [NSTimerscheduledTimerWithTimeInterval:self.durationTimertarget:selfselector:@selector(nextImage)userInfo:nilrepeats:YES];

    

    NSRunLoop *runLoop = [NSRunLoopmainRunLoop];

    [runLoop addTimer:self.timerforMode:NSRunLoopCommonModes];

}


/**

 *  定时器停止工作

 */

-(void)pauseTimer

{

    [self.timerinvalidate];

    self.timer =nil;

}


-(void)nextImage

{

    CGFloat width =self.bannerScrollView.frame.size.width;

    NSInteger index =self.pageView.currentPage;

   

    if (index == self.count +1) {

        index = 0;

    } else {

        index++;

    }

    [self.bannerScrollViewsetContentOffset:CGPointMake((index +1) * width,0)animated:YES];

}


/**

 *  选择图片事件

 *

 *  @param tap 手势

 */

-(void)chooseImage:(UITapGestureRecognizer*)tap

{

    if (self.delegate) {

        

        [self.delegatedidSelectImage:(tap.view.tag -100)];

    }

}



/**

 *  开始拖动的时候,定时器停止

 *

 *  @param scrollView 滚动视图

 */

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

    [selfpauseTimer];

}


/**

 *  停止拖动的时,定时器启动

 */

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{

    [selfcreateTimer];

}


-(void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    CGFloat width =self.bannerScrollView.frame.size.width;

    /**

     *  目的是计算page

     *  其实用 self.bannerScrollView.contentOffset.x width 也可以,

     *  但为了更加严谨点,取图片的中点 width

     */

    NSInteger index = (self.bannerScrollView.contentOffset.x + width *0.5) / width;

    

    if (index == self.count +2) {

        index = 1;

    } else if(index ==0) {

        index = self.count;

    }

    self.pageView.currentPage = index -1;

   

}


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

    [selfscrollViewDidEndDecelerating:scrollView];

}


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

    CGFloat width =self.bannerScrollView.frame.size.width;

    int index = (self.bannerScrollView.contentOffset.x + width *0.5) / width;

    if (index == self.count +1) {

        

        [self.bannerScrollViewsetContentOffset:CGPointMake(width,0) animated:NO];

    } else if (index ==0) {

        

        [self.bannerScrollViewsetContentOffset:CGPointMake(self.count * width,0) animated:NO];

    }

}


@end


在使用的viewController中的使用方法:

#import "ViewController.h"

#import "JJRollBanner.h"


@interface ViewController ()<JJRollBannerDelegate>

{

    JJRollBanner *rollView;

   

}

@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    rollView = [[JJRollBanneralloc] initWithFrame:CGRectMake(0,20, self.view.frame.size.width,180)];

    

    NSMutableArray *array = [NSMutableArrayarray];

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

    {

        NSString *string = [NSStringstringWithFormat:@"img_%02d.jpg", i +1];

        [array addObject:string];

    }

    [rollViewsetLoactionImageArray:array];

    rollView.delegate =self;

    

    [self.viewaddSubview:rollView];

}



-(void)didSelectImage:(NSInteger)index

{

    NSLog(@"点击了第 %ld张图片 ", index +1);

}



1 0