iOS中的轮播----collectionView

轮播 顾名思义就是无限滚动. 在日常开发中, 我们经常需要对一些广告和一些图片进行自动的轮播.
一般我们想到的是使用UIScrollView, 上面添加多个照片, 然后前后各添加一张照片, 实现无限滚动, 这样做存在一个问题就是, 如果 图片数量为三五张完全没问题, 但是如果有十几张照片或者浏览照片库的时候就不得不考虑性能问题, 造成内存浪费性能低. 所以今天我们用collectionView的重用机制优化内存.

实现过程:
首先创建collectionView使用collection的flowLayout布局
flowLayout的代码
.h

#import 

@interface LayoutFirst : UICollectionViewFlowLayout

@end

.m

#import "LayoutFirst.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width


@implementation LayoutFirst

- (instancetype)init {
    self = [super init];
    if (self) {
        // item size
        self.itemSize = CGSizeMake(WIDTH,  300);
        self.minimumLineSpacing = 0;
        self.minimumInteritemSpacing = 0;
//        self.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}
@end

还要自定义cell 在cell中创建图片
自定义cell的.h

#import 
@interface CellForImage : UICollectionViewCell
@property (nonatomic, copy) NSString *string;
@end

.m

#import "CellForImage.h"
@interface CellForImage ()
@property (nonatomic, strong) UIImageView *imageViewOfItem;
@end
@implementation CellForImage
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
// 在这里创建子控件但是布局要写到layoutSubviews中
        self.imageViewOfItem = [[UIImageView alloc] init];
        [self addSubview:_imageViewOfItem];
    }
    return self;
}
// 子控件的布局
- (void)layoutSubviews {
// 注意父类的调用
    [super layoutSubviews];
    self.imageViewOfItem.frame = self.bounds;
    self.imageViewOfItem.backgroundColor = [UIColor cyanColor];
}
// cell中照片的setter方法string是照片的name
- (void)setString:(NSString *)string {
    _string = [string copy];
    self.imageViewOfItem.image = [UIImage imageNamed:string];
}
@end

写完上述布局就可以在VC中创建collectionView了

#import "ViewController.h"
#import "LayoutFirst.h"
#import "CellForImage.h"

@interface ViewController () 

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) LayoutFirst *flowLayout;

@property (nonatomic, strong) NSMutableArray *mArrOfPhoto;

@property (nonatomic, strong) UIPageControl *page;

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation ViewController

#pragma mark ------------ 处理照片的数组  -----------
- (NSArray *)arrayOfPhoto {

    if (_mArrOfPhoto == nil) {
        
        _mArrOfPhoto = [NSMutableArray array];
        for (int i = 1; i < 11; i++) {
            
            NSString *photoName = [NSString stringWithFormat:@"%d", i];
            [_mArrOfPhoto addObject:photoName];
        }
    }
    return _mArrOfPhoto;   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.navigationController.navigationBar.translucent = NO;
    [self arrayOfPhoto];
// 创建collectionView
    [self createCollrctionView];
    // 创建pageControl
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(150, 270, self.view.bounds.size.width - 300, 20)];
    [self.view addSubview:self.page];
    self.page.numberOfPages = self.mArrOfPhoto.count;
    // 添加定时器
    [self addNSTimer];
}
#pragma mark ------------  创建collectionView的实现必须的协议  -----------
- (void)createCollrctionView {
  // flowLayout的初始化可以对item进行设置: 大小, 以及周边距
    self.flowLayout = [[LayoutFirst alloc] init];
    // 创建对象
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 300) collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.collectionView registerClass:[CellForImage class] forCellWithReuseIdentifier:@"pool"];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:50] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
}
// 返回item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _mArrOfPhoto.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CellForImage *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    cell.string = _mArrOfPhoto[indexPath.item];
    return cell;
}
// 这里是返回分区的个数(默认为1)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 100;
}
#pragma mark ------------  添加定时器  -----------
- (void)addNSTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
    // 添加到runloop中
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
// 定时器的作用, 下一个图
- (void)next {
    // 获取当前正在展示的位置
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
// 反回中间的数据100是返回的分区个数
    NSIndexPath *currentIndexPathRest = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:100 / 2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathRest atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    // 计算出下一个需要展示的位置
    NSInteger nextItem = currentIndexPathRest.item + 1;
    NSInteger nextSection = currentIndexPathRest.section;
    if (nextItem == self.mArrOfPhoto.count) {   
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    // 通过动画滚到下一个位置
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    self.page.currentPage = nextItem;
}
#pragma mark ------------  当用户拖拽的时候就调用移除定时  -----------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeNSTimer];
}
- (void)removeNSTimer {
    [self.timer invalidate];
    self.timer = nil;
}
#pragma mark ------------  当用户停止拖拽的时候调用  -----------
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addNSTimer];
}
#pragma mark ------------  设置页码  -----------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width) % self.mArrOfPhoto.count;
    self.page.currentPage = page;
}

这里面主要用到NSTimer的一些简单用法和如下这个方法

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

// 1)、(NSTimeInterval)ti : 预订一个Timer,设置一个时间间隔。 
表示输入一个时间间隔对象,以秒为单位,一个>0的浮点类型的值,如果该值<0,系统会默认为0.1。
// 2)、target:(id)aTarget : 表示发送的对象,如self
// 3)、selector:(SEL)aSelector : 方法选择器,在时间间隔内,选择调用一个实例方法
// 4)、userInfo:(nullable id)userInfo : 需要传参,可以为nil
// 5)、repeats:(BOOL)yesOrNo : 当YES时,定时器会不断循环直至失效或被释放,当NO时,定时器会循环发送一次就失效。
// 开启定时器:
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// 关闭定时器
[self.timer invalidate];

这种方法实现的无限轮播图有一个小缺陷, 就不说了, 自己慢慢发现吧.

你可能感兴趣的:(iOS中的轮播----collectionView)