輪播器(一)--UIScrollView實現圖片輪播

此篇文章主要介紹如何採用UIScrollView來實現輪播圖,加入定時器來實現自動輪播

#import <UIKit/UIKit.h>

@protocol CarouselDelegate <NSObject>

//圖片的點擊事件
-(void)clickedAtIndex:(NSInteger)index;

@end

@interface CarouselView1 : UIView

//代理
@property (nonatomic,assign) id<CarouselDelegate> delegate;

//初始化
-(instancetype)initWithFrameAndData:(CGRect)frame data:(NSMutableArray *)dataModel;

//開啓自動滾動
-(void)startAutoScroll;

//停止自動滾動
-(void)stopAutoScroll;

@end
#import "CarouselView1.h"
#import "UIImageView+WebCache.h"
#import "CarouselModel.h"

@interface CarouselView1 ()<UIScrollViewDelegate>
//裝載輪播圖的scrollView
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
//頁碼
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
//數據源
@property (strong,nonatomic) NSMutableArray *dataArr;
//滾動的計時器
@property (strong,nonatomic) NSTimer *timer;

//是否開啓自動滾動,默認不開啓
@property (assign,nonatomic) BOOL autoScroll;
@end

@implementation CarouselView1

-(instancetype)initWithFrameAndData:(CGRect)frame data:(NSMutableArray *)dataModel
{
    if (self = [super initWithFrame:frame]) {
        self = [[NSBundle mainBundle] loadNibNamed:@"CarouselView1" owner:nil options:nil][0];
        self.frame = frame;
        self.dataArr = dataModel;
        [self initCarouselView];
    }
    return self;
}

-(void)initCarouselView
{

    CGFloat imageW = self.frame.size.width;
    CGFloat imageH = self.frame.size.height;
    CGFloat imageY = 0;
    CGFloat imageX = 0;
    
    //初始化
    self.scrollView.delegate = self;
    self.scrollView.backgroundColor = [UIColor lightGrayColor];
    
    //添加圖片
    for (int i = 0; i < self.dataArr.count; i++) {
        imageX = i * imageW;
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(imageX, imageY, imageW, imageH)];
        imageView.tag = 1000 + i;
        imageView.userInteractionEnabled = YES;
        CarouselModel *model = [self.dataArr objectAtIndex:i];
        [imageView sd_setImageWithURL:[[NSURL alloc] initWithString:model.imageUrl] placeholderImage:[UIImage imageNamed:@"1"]];
        [self.scrollView addSubview:imageView];
        
        //添加imageView的點擊事件
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewTaped:)];
        [imageView addGestureRecognizer:tap];
    }
    
    //設置內容區域
    self.scrollView.contentSize = CGSizeMake(self.dataArr.count * imageW, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    
    //設置分頁頁數
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = self.dataArr.count;
    self.pageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    self.pageControl.pageIndicatorTintColor = [UIColor grayColor];
    self.pageControl.userInteractionEnabled = NO;
    
    if(self.autoScroll)
    {
        [self startTimer];
    }
}

-(void)imageViewTaped:(UITapGestureRecognizer *)sender
{
    NSLog(@"+++++++++:%ld",sender.view.tag);
    if ([self.delegate respondsToSelector:@selector(clickedAtIndex:)]) {
        [self.delegate clickedAtIndex:sender.view.tag];
    }
}

//開始自動滾動
- (void)startTimer
{
    self.timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

//開啓自動滾動
-(void)startAutoScroll
{
    self.autoScroll = YES;
    [self startTimer];
}

//停止自動滾動
-(void)stopAutoScroll
{
    self.autoScroll = NO;
    [self.timer invalidate];
    self.timer = nil;
}

- (void)updateTimer
{
    self.pageControl.currentPage = (self.pageControl.currentPage + 1) % self.dataArr.count;
    [self pageChanged:self.pageControl];
}

#pragma mark - 分頁控件監聽方法
- (void)pageChanged:(UIPageControl *)page
{
    CGFloat x = page.currentPage * self.scrollView.bounds.size.width;
    [self.scrollView setContentOffset:CGPointMake(x, 0) animated:YES];
}

#pragma mark - 滾動視圖代理方法
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 根據contentOffset計算頁數
    NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    self.pageControl.currentPage = page;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.timer)
    {
        return;
    }
    self.pageControl.currentPage = (scrollView.contentOffset.x + scrollView.frame.size.width * 0.5) / scrollView.frame.size.width;
}

//手動滑動開始時,停止自動滾動
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (self.autoScroll) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

//手動滑動停止時,開啓自動滾動
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.autoScroll) {
        [self startTimer];
    }
}

#pragma mark 懶加載

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc]init];
    }
    return _dataArr;
}

@end

@interface CarouselModel : NSObject

//輪播圖的地址
@property(copy,nonatomic) NSString *imageUrl;

//超鏈接內容的地址
@property(copy,nonatomic) NSString *contentUrl;

//文本顯示內容
@property(copy,nonatomic) NSString *labelText;

@end



VC中使用

self.automaticallyAdjustsScrollViewInsets = NO;
    
    NSMutableArray *dataList = [[NSMutableArray alloc]init];
    NSMutableArray *dataArr = [[NSMutableArray alloc]initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"carouselArr.plist" ofType:nil]];
    for (NSDictionary *dic in dataArr) {
        CarouselModel *model = [[CarouselModel alloc]init];
        model.imageUrl = [dic objectForKey:@"imageUrl"];
        model.contentUrl = [dic objectForKey:@"contentUrl"];
        model.labelText = [dic objectForKey:@"textLable"];
        [dataList addObject:model];
    }
    
    CarouselView1 *view1 = [[CarouselView1 alloc]initWithFrameAndData:CGRectMake(20, 100, self.view.frame.size.width - 40, (self.view.frame.size.width - 40) * 0.5) data:dataList];
    view1.delegate = self;
//    開啓自動滾動
    [view1 startAutoScroll];
    [self.view addSubview:view1];




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章