关闭

iOS UICollectionView 实现轮播图

标签: ios轮播图
2957人阅读 评论(0) 收藏 举报
分类:

利用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
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:104595次
    • 积分:1677
    • 等级:
    • 排名:千里之外
    • 原创:65篇
    • 转载:15篇
    • 译文:0篇
    • 评论:19条
    博客专栏
    微信思密达
    最新评论