UICollectionView实现无限滚动视图

先看效果

UICollectionView实现无限滚动视图_第1张图片
demo.gif

实现思路

  1. 将原数据的总量x比较大的一个数字作为collectionVew的数据原总量
  2. 初始化时滚动到一倍数为一半的位置
  3. 拖拽完成时定位回中间的位置
// 轮播倍数
static const int kLoopMaxMultiple = 1000;
// 一半轮播倍数
static const int kHalfLoopMaxMultiple = kLoopMaxMultiple / 2;

- (void)startScroll {
    // 滚动到中间位置
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:kHalfLoopMaxMultiple * self.datas.count inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
    [self resumeTimer];
}

/**
 获取scrollView的index
 
 @param scrollView scrollView
 @return index
 */
- (NSInteger)indexWithScrollView:(UIScrollView * _Nonnull)scrollView {
    NSInteger index = roundf(scrollView.contentOffset.x) / scrollView.frame.size.width;
    index = (index) % self.datas.count;
    return index;
}

/**
 滚动到指定索引

 @param scrollView scrollView
 */
- (void)scrollToIndex:(UIScrollView *)scrollView {
    NSInteger index = [self indexWithScrollView:scrollView];
    NSInteger item = kHalfLoopMaxMultiple* self.datas.count + index;
    if (index == self.datas.count - 1) {
        item = (kHalfLoopMaxMultiple - 1) * self.datas.count + index;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem: item inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

自动滚动

通过NSTimer实现定时滚动,当开始拖动时取消计时器,完成拖动后恢复

/**
 恢复定时器
 */
- (void)resumeTimer {
    // 将定时器添加到主线程
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


/**
 暂停定时器
 */
- (void)pauseTimer {
    [self.timer invalidate];
    _timer = nil;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self pauseTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollToIndex:scrollView];
    [self resumeTimer];
}

完整代码

ViewController.m

//
//  ViewController.m
//  iOSDemo
//
//  Created by yizhaorong on 2018/1/7.
//  Copyright © 2018年 yizhaorong. All rights reserved.
//

#import "ViewController.h"
#import "YYCollectionViewCell.h"

// 轮播倍数
static const int kLoopMaxMultiple = 1000;
// 一半轮播倍数
static const int kHalfLoopMaxMultiple = kLoopMaxMultiple / 2;

@interface ViewController () 
// 滚动主视图
@property (nonatomic, strong) UICollectionView *collectionView;
// 数据
@property (nonatomic, strong) NSMutableArray *datas;
// 背景色
@property (nonatomic, strong) NSMutableArray *colors;
// 分页指示器
@property (nonatomic, strong) UIPageControl *pageControl;
// 定时器
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ViewController

#pragma mark - LifeCircle
- (void)viewDidLoad {
    [super viewDidLoad];
    // 初始化数据
    [self setupDatas];
    // 初始化子视图
    [self setupSubviews];
    // 开始滚动
    [self startScroll];
}

- (void)setupSubviews {
    CGFloat top = 64;
    CGFloat height = self.view.bounds.size.height - 2 * top;
    CGSize itemSize = CGSizeMake(self.view.bounds.size.width, height);
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = itemSize;
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, top, itemSize.width, height) collectionViewLayout:layout];
    [_collectionView registerClass:[YYCollectionViewCell class] forCellWithReuseIdentifier:@"YYCollectionViewCell"];
    _collectionView.pagingEnabled = YES;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [self.view addSubview:_collectionView];
    
    _pageControl = [UIPageControl new];
    _pageControl.numberOfPages = self.datas.count;
    _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    _pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    CGSize pageControlSize = [_pageControl sizeForNumberOfPages:self.datas.count];
    CGFloat pageControlX = (self.view.bounds.size.width - pageControlSize.width) / 2;
    CGFloat pageControlY = CGRectGetMaxY(_collectionView.frame) - pageControlSize.height - 8;
    _pageControl.frame = CGRectMake(pageControlX, pageControlY, pageControlSize.width, pageControlSize.height);
    [self.view addSubview:_pageControl];
}

- (void)setupDatas {
    _datas = [NSMutableArray array];
    _colors = [NSMutableArray array];
    for (int i = 0; i < 3; ++i) {
        NSString *title = [NSString stringWithFormat:@"第%i个视图", i + 1];
        UIColor *color = [UIColor colorWithRed:(arc4random_uniform(255) / 255.0) green:(arc4random_uniform(255) / 255.0) blue:(arc4random_uniform(255) / 255.0) alpha:1];
        [_datas addObject:title];
        [_colors addObject:color];
        
    }
}

- (void)startScroll {
    // 滚动到中间位置
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:kHalfLoopMaxMultiple * self.datas.count inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:0 animated:NO];
    [self resumeTimer];
}

#pragma mark - Private
/**
 获取scrollView的index
 
 @param scrollView scrollView
 @return index
 */
- (NSInteger)indexWithScrollView:(UIScrollView * _Nonnull)scrollView {
    NSInteger index = roundf(scrollView.contentOffset.x) / scrollView.frame.size.width;
    index = (index) % self.datas.count;
    return index;
}

/**
 滚动到指定索引

 @param scrollView scrollView
 */
- (void)scrollToIndex:(UIScrollView *)scrollView {
    NSInteger index = [self indexWithScrollView:scrollView];
    NSInteger item = kHalfLoopMaxMultiple* self.datas.count + index;
    if (index == self.datas.count - 1) {
        item = (kHalfLoopMaxMultiple - 1) * self.datas.count + index;
    }
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem: item inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

/**
 恢复定时器
 */
- (void)resumeTimer {
    // 将定时器添加到主线程
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}


/**
 暂停定时器
 */
- (void)pauseTimer {
    [self.timer invalidate];
    _timer = nil;
}


/**
 自动滚动

 @param timer 定时器
 */
- (void)update:(NSTimer *)timer{
    NSInteger index = [self indexWithScrollView:self.collectionView] + 1;
    NSInteger item = kHalfLoopMaxMultiple * self.datas.count + index % self.datas.count;
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem: item inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.datas.count * kLoopMaxMultiple;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    YYCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YYCollectionViewCell" forIndexPath:indexPath];
    NSInteger index = indexPath.item % self.datas.count;
    cell.contentView.backgroundColor = self.colors[index];
    cell.titleLabel.text = self.datas[index];
    return cell;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSInteger index = [self indexWithScrollView:scrollView];
    self.pageControl.currentPage = index;
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self scrollToIndex:scrollView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self pauseTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollToIndex:scrollView];
    [self resumeTimer];
}

#pragma mark - Setter And Getter
- (NSTimer *)timer {
    if (!_timer) {
        // 设置时钟动画 定时器
        _timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(update:) userInfo:nil repeats:YES];
    }
    return _timer;
}

@end

YYCollectionViewCell.m

//
//  YYCollectionViewCell.m
//  iOSDemo
//
//  Created by yizhaorong on 2018/1/7.
//  Copyright © 2018年 yizhaorong. All rights reserved.
//

#import "YYCollectionViewCell.h"

@implementation YYCollectionViewCell

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

- (void)setupSubviews {
    _titleLabel = [UILabel new];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont boldSystemFontOfSize:32];
    [self.contentView addSubview:_titleLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.titleLabel.frame = self.bounds;
}

@end

你可能感兴趣的:(UICollectionView实现无限滚动视图)