iOS UICollectionView 实现轮播图

Posted HeathHsia

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS UICollectionView 实现轮播图相关的知识,希望对你有一定的参考价值。

利用UICollectionView 实现轮播图 :



<span style="font-size:24px;">//
//  ViewController.m
//  CollectionPhotosView
//
//  Created by 帝炎魔 on 16/5/30.
//  Copyright © 2016年 帝炎魔. All rights reserved.
//

/**
 *  UICollectionView  实现轮播图的实现
    将定时器NSTimer 加入到mainrunloop中实现定时轮播
 *
    CollectionCell 和tableViewCell 用法不太一样, CollectionCell 需要注册, 告诉系统这种标识对应的cell是什么类型的cell, 如果缓冲池中没有, 自动创建这种类型的cell
 
 *
 */

#import "ViewController.h"
#import "News.h"
#import "YYCell.h"

#define kWidth [UIScreen mainScreen].bounds.size.width
#define kHeight [UIScreen mainScreen].bounds.size.height

#define MaxSections 100

@interface ViewController () <UICollectionViewDelegate, UICollectionViewDataSource>





@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) UIPageControl *pageControl;

@property (nonatomic, strong) NSMutableArray *news;

@property (nonatomic, strong) NSTimer *timer;


@end

@implementation ViewController

- (void)viewDidLoad 
    [super viewDidLoad];
    
    [self.view addSubview:self.collectionView];
    
    [self.view addSubview:self.pageControl];
    
    // 注册cell
    [self.collectionView registerClass:[YYCell class] forCellWithReuseIdentifier:@"Cell"];

    
    // 添加定时器 实现轮播功能呢
    [self addTimer];
    
    
    // Do any additional setup after loading the view, typically from a nib.


- (void)addTimer

    _timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextPage) userInfo:NULL repeats:YES];
    


// 定时器的内容
- (void)nextPage

    // 获取当前的 indexPath
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    NSIndexPath *currentIndexPathSet = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:MaxSections / 2];
    
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathSet atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    // 设置下一个滚动的item的indexPath
    NSInteger nextItem = currentIndexPathSet.item + 1;
    NSInteger nextSection = currentIndexPathSet.section;
    if (nextItem == self.news.count) 
        // 当item等于轮播图的总个数的时候
        // item等于0, 分区加1
        // 未达到的时候永远在50分区中
        nextItem = 0;
        nextSection ++;
    
    // NSLog(@"----%ld---%ld", nextItem, nextSection);
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    


#pragma mark ----ScrollView 代理方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

    // 添加定时器
    [self addTimer];


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView

    // 移除定时器
    [self.timer invalidate];
    self.timer = nil;


-(void)scrollViewDidScroll:(UIScrollView *)scrollView

    // 滚动时 动态设置 pageControl.currentPage
    int page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width + 0.5) % self.news.count;
    self.pageControl.currentPage = page;


#pragma mark ---- 创建集合视图

// 创建集合视图
- (UICollectionView *)collectionView
   
    if (!_collectionView) 
        // 创建UICollectionViewFlowLayout约束对象
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        // 设置item的Size大小
        flowLayout.itemSize = CGSizeMake(kWidth, kHeight);
        // 设置uicollection 的 横向滑动
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flowLayout.minimumLineSpacing = 0;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) collectionViewLayout:flowLayout];
        
        // 设置代理
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        // 设置不展示滑动条
        _collectionView.showsHorizontalScrollIndicator = NO;
        // 设置整页滑动
        _collectionView.pagingEnabled = YES;
        _collectionView.backgroundColor = [UIColor clearColor];

        
        // 设置当前collectionView 到哪个位置(indexPath row 0 section 取中间(50个))
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:MaxSections / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        
       
        
    
    return _collectionView;
    


- (UIPageControl *)pageControl

    if (!_pageControl) 
        UIPageControl *pageControl = [[UIPageControl alloc] init];
        pageControl.center = CGPointMake(kWidth / 2, kHeight - 100);
        pageControl.numberOfPages = _news.count;
        pageControl.bounds = CGRectMake(0, 0, 150, 40);
        pageControl.enabled = NO;
        pageControl.pageIndicatorTintColor = [UIColor blueColor];
        pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        [self.view addSubview:pageControl];
        _pageControl = pageControl;
    
    return _pageControl;


#pragma mark --- 数据源
- (NSMutableArray *)news

    if (!_news) 
        NSString *path = [[NSBundle mainBundle] pathForResource:@"resource.plist" ofType:nil];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        _news = [NSMutableArray array];
        for (NSDictionary *dic in arr) 
            [_news addObject:[News newsWithDict:dic]];
        
    
    return _news;



#pragma mark --- 实现collectionView代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

    return MaxSections;

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

    return self.news.count;


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

    static NSString *string = @"Cell";
    YYCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:string forIndexPath:indexPath];
    if (!cell) 
        cell = [[YYCell alloc] init];
    
    cell.news = self.news[indexPath.row];
    return cell;


- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.


@end
</span>



以上是关于iOS UICollectionView 实现轮播图的主要内容,如果未能解决你的问题,请参考以下文章

iOS UICollectionView无限轮播

iOS UICollectionView无限轮播

使用 UICollectionView 实现首页卡片轮播效果

UICollectionView实现无限轮播

iOS:实现图片的无限轮播---之使用第三方库SDCycleScrollView

iOS无限轮播视图