使用UICollectionView实现循环轮播图片的功能

1、使用方法:

NSMutableArray *listArray = @[].mutableCopy;

    for (NSInteger i = 0; i < 5; i++) {

        ZGCyclePictureModel *model = [[ZGCyclePictureModel alloc] init];

        model.type = ZGCyclePictureTypeLocal;

        model.image = [UIImage imageNamed:[NSString stringWithFormat:@"CircularBrowsePicture-0%ld.JPG", i + 1]];

        [listArray addObject:model];

    }

    

    __weak typeof(self) weakSelf = self;

   self.cycleView = [ZGCycleCollectionView showPictures:listArray onSelect:^(ZGCyclePictureModel *model, NSInteger index) {

        

        weakSelf.cycleView.isAutoBrowse = YES;

        weakSelf.cycleView.scrollDirection = UICollectionViewScrollDirectionHorizontal;

        NSLog(@"点击的第%@张图片", @(index));

    } didScroll:^(ZGCyclePictureModel *model, NSInteger index) {

        

        weakSelf.title = [NSString stringWithFormat:@"第%@张图片", @(index)];

    }];

    self.cycleView.scrollDirection = UICollectionViewScrollDirectionVertical; //    UICollectionViewScrollDirectionHorizontal

    self.cycleView.isAutoBrowse = NO;

    [self.contentView addSubview:self.cycleView];

    

    [self.cycleView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(70);

        make.left.right.mas_equalTo(0);

        make.height.mas_equalTo(self.cycleView.mas_width).multipliedBy(0.75);

    }];

    


2、代码的.h和.m文件:

//

//  ZGCycleCollectionView.h

//  SummaryDemo

//

//  Created by zhaogang on 2018/4/28.

//


#import <UIKit/UIKit.h>

#import "ZGCyclePictureModel.h"


typedef void (^ZGCycleCollectionViewSelectHandler)(ZGCyclePictureModel *model, NSInteger index);

typedef void (^ZGCycleCollectionViewDidScrollHandler)(ZGCyclePictureModel *model, NSInteger index);



@interface ZGCycleCollectionView : UIView


@property (nonatomic, assign) BOOL                             isAutoBrowse;

@property (nonatomic, assign) UICollectionViewScrollDirection   scrollDirection;


+ (ZGCycleCollectionView *)showPictures:(NSArray<ZGCyclePictureModel *> *)pictures onSelect:(ZGCycleCollectionViewSelectHandler)select didScroll:(ZGCycleCollectionViewDidScrollHandler)scroll;


// 关闭定时器

- (void)closeTimer;



@end




//

//  ZGCycleCollectionView.m

//  SummaryDemo

//

//  Created by zhaogang on 2018/4/28.

//


#import "ZGCycleCollectionView.h"

#import "ZGCycleCollectionCell.h"

#import "Masonry.h"

#import "SDWebImageManager.h"

#import "UIView+WebCache.h"

#import "UIImageView+WebCache.h"


@interface ZGCycleCollectionView ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout>


@property (nonatomic, strong) UICollectionViewFlowLayout  *flowLayout;

@property (nonatomic, strong) UICollectionView            *collectionView;

@property (nonatomic, strong) NSTimer                     *timer;

@property (nonatomic, assign) NSInteger                   currentPage;


@property (nonatomic, assign) NSInteger                   sectionCount;

@property (nonatomic, strong) NSMutableArray              *pictures;


@property (nonatomic, copy) ZGCycleCollectionViewSelectHandler selectHandler;

@property (nonatomic, copy) ZGCycleCollectionViewDidScrollHandler didScrollHandler;


@end


@implementation ZGCycleCollectionView


+ (ZGCycleCollectionView *)showPictures:(NSArray<ZGCyclePictureModel *> *)pictures onSelect:(ZGCycleCollectionViewSelectHandler)select didScroll:(ZGCycleCollectionViewDidScrollHandler)scroll

{

    ZGCycleCollectionView *view = [[ZGCycleCollectionView alloc] initPictures:pictures onSelect:select didScroll:scroll];

    return view;

}


- (instancetype)initPictures:(NSArray<ZGCyclePictureModel *> *)pictures onSelect:(ZGCycleCollectionViewSelectHandler)select didScroll:(ZGCycleCollectionViewDidScrollHandler)scroll

{

    if (self = [super init]) {

        self.selectHandler = select;

        self.didScrollHandler = scroll;

        [self createUI];

        self.pictures = pictures.mutableCopy;

    }

    return self;

}


- (void)createUI

{

    self.sectionCount = 3;

    

    // Init flowLayout.

    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];

    self.flowLayout.minimumLineSpacing = 0;

    

    // Init UICollectionView.

    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.flowLayout];

    self.collectionView.showsHorizontalScrollIndicator = YES;

    self.collectionView.showsVerticalScrollIndicator   = YES;

    self.collectionView.pagingEnabled                  = YES;

    self.collectionView.backgroundColor                = [UIColor yellowColor];

    self.collectionView.delegate   = self;

    self.collectionView.dataSource = self;

    self.collectionView.bounces = NO; // 防止滑动快的时候右侧出现白的

    [self.collectionView registerClass:[ZGCycleCollectionCell class] forCellWithReuseIdentifier:@"ZGCycleCollectionCell"];

    [self addSubview:self.collectionView];

    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.top.left.right.bottom.equalTo(self);

    }];

}


- (void)layoutSubviews

{

    [super layoutSubviews];

    self.flowLayout.itemSize = CGSizeMake(self.frame.size.width, (self.frame.size.width)*3/4);

}


- (void)setPictures:(NSMutableArray *)pictures

{

    _pictures = pictures;

    [self.collectionView reloadData];

    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1]

                                atScrollPosition:(self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? UICollectionViewScrollPositionLeft : UICollectionViewScrollPositionTop)

                                        animated:NO];

}


- (void)setIsAutoBrowse:(BOOL)isAutoBrowse

{

    _isAutoBrowse = isAutoBrowse;

    

    if (_isAutoBrowse) {

        [self openTimer];

    }

    else {

        [self closeTimer];

    }

}


- (void)setScrollDirection:(UICollectionViewScrollDirection)scrollDirection

{

    _scrollDirection = scrollDirection;

    self.flowLayout.scrollDirection = _scrollDirection;

}


// 开启定时器

- (void)openTimer

{

    [self closeTimer];

    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction)

                                                userInfo:nil

                                                 repeats:YES];

    

    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

}


// 关闭定时器

- (void)closeTimer

{

    [self.timer invalidate];

    self.timer = nil;

}


- (void)timerAction

{

    if (_pictures.count == 0) {

        return;

    }

    

    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];

    

    NSInteger newRow     = (currentIndexPath.row + 1) % _pictures.count;

    NSInteger newSection = currentIndexPath.section + (newRow == 0 ? 1 : 0);

    

    BOOL isAnimated = YES;

    if (newSection == self.sectionCount - 1) {

        newSection = 0;

        isAnimated = NO;

    }

    

    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:newRow inSection:newSection];

    

    [self.collectionView scrollToItemAtIndexPath:newIndexPath

                                atScrollPosition:(self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? UICollectionViewScrollPositionLeft : UICollectionViewScrollPositionTop)

                                        animated:isAnimated];

}



#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height);

}


-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    return UIEdgeInsetsMake(0, 0, 0, 0); //上、左、下、右

}


//横向间距

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section

{

    return 0;

}


//纵向间距

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section

{

    return 0;

}


#pragma mark -  UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return self.sectionCount;

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    

    return _pictures.count;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *cellIdentifier = @"ZGCycleCollectionCell";

    ZGCycleCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];

    [self setImageWithModel:_pictures[indexPath.row] imageView:cell.imageView];

    cell.titleLabel.text = [NSString stringWithFormat:@"第%@张图片", @(indexPath.row)];

    return cell;

}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    

    // 点击某张图片

    if (self.selectHandler) {

        self.selectHandler(_pictures[indexPath.row], indexPath.row);

    }

}


- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath

{

    //        [cell willDisplay];

}


- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath

{

    //        [cell didEndDisplay];

}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

{

    // 只有手势滑动才会触发

    if (_isAutoBrowse) {

        [self closeTimer];

    }

    

    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];

    

    if (currentIndexPath.section == 0 || currentIndexPath.section == self.sectionCount - 1) {

        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:currentIndexPath.row inSection:1]

                                    atScrollPosition:(self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal ? UICollectionViewScrollPositionLeft : UICollectionViewScrollPositionTop)

                                            animated:NO];

    }

}


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

{

    // 只有手势滑动才会触发

    if (_isAutoBrowse) {

        [self openTimer];

    }

}


// 无论手势和定时器都会触发

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    if (_pictures.count == 0) {

        return;

    }

    

    NSInteger newValue = [self currentIndex];

    

    if (self.currentPage != newValue) {

        self.currentPage = newValue;

        if (self.didScrollHandler) {

            self.didScrollHandler(_pictures[self.currentPage], self.currentPage);

        }

    }

}


#pragma mark - 私有方法

- (NSInteger)currentIndex

{

    NSInteger index = 0;

    if (self.flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {

        index = (self.collectionView.contentOffset.x + self.flowLayout.itemSize.width * 0.5) / self.flowLayout.itemSize.width;

    }

    else {

        index = (self.collectionView.contentOffset.y + self.flowLayout.itemSize.height * 0.5) / self.flowLayout.itemSize.height;

    }

    return index % _pictures.count;

}


- (void)setImageWithModel:(ZGCyclePictureModel *)model imageView:(UIImageView *)imageView

{

    if (model.type == ZGCyclePictureTypeLocal) {

        imageView.image = model.image;

    }

    else {

        imageView.sd_imageTransition = SDWebImageTransition.fadeTransition;

        [imageView sd_setShowActivityIndicatorView:YES];

        [imageView sd_setIndicatorStyle:UIActivityIndicatorViewStyleGray];

        [imageView sd_setImageWithURL:model.imageUrl placeholderImage:[UIImage imageNamed:@"animation.png"]];

    }

}


- (void)dealloc

{

    

}


@end



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值