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>



  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值