易采站长站为您分析IOS图片无限轮播器的实现原理的相关资料,需要的朋友可以参考下
首先实现思路:整个collectionView中只有2个cell.中间始终显示第二个cell.
滚动:向前滚动当前cell的脚标为0,向后滚动当前的cell脚标为2.利用当前cell的脚标减去1,得到+1,或者-1,来让图片的索引加1或者减1,实现图片的切换.
声明一个全局变量index来保存图片的索引,用来切换显示在当前cell的图片.
在滚动前先让显示的cell的脚标变为1.代码viewDidLoad中设置
完成一次滚动结束后,代码再设置当前的cell为第二个cell(本质上就是让当前显示的cell的脚标为1)
最后一个有一个线程问题就是:当你连续滚动的时候,最后停止,当前显示的图片会闪动,因为是异步并发执行的,线程不安全导致.解决办法:让滚动完成后设置cell的代码加入主队列执行即可.
准备工作,创建collectionViewController,storyboard,进行类绑定,cell绑定,cell可重用标识绑定.
创建的cell.h文件
//
// PBCollectionCell.h
// 无限滚动
//
// Created by 裴波波 on 16/3/30.
// Copyright © 2016年 裴波波. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface PBCollectionCell : UICollectionViewCell
@property(nonatomic,strong)UIImage * img;
@end
•cell.m文件
//
// PBCollectionCell.m
// 无限滚动
//
// Created by 裴波波 on 16/3/30.
// Copyright © 2016年 裴波波. All rights reserved.
//
#import "PBCollectionCell.h"
@interface PBCollectionCell ()
//不要忘记给collectionView的cell上设置图片框,并拖线到cell分类中
@property (strong, nonatomic) IBOutlet UIImageView *imgView;
@end
@implementation PBCollectionCell
//重写img的set方法来个cell进行赋值.(当调用cell.img = img的时候回调用set ..img的方法)
-(void)setImg:(UIImage *)img{
_img = img;
self.imgView.image = img;
}
@end
控制器的代码详解
//
// ViewController.m
// 无限滚动
//
// Created by 裴波波 on 16/3/30.
// Copyright © 2016年 裴波波. All rights reserved.
//
#import "ViewController.h"
#import "PBCollectionCell.h"
//定义宏图片的个数
#define kPictureCount 3
@interface ViewController ()
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
/**
* 图片的索引
*/
@property(nonatomic,assign) NSInteger index;
@end
•声明全局变量index为了拼接滚动过程中切换的图片的索引
@implementation ViewController
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return kPictureCount;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
static NSString * ID = @"cell";
PBCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
//图片索引只有下一站或者上一张,即+1,或者-1,为了切换图片
//中间的cell的脚标是1,滚动后脚标是2或者0,凑成next值为+1或者-1(让图片索引+1或者-1来完成切换图片),则
NSInteger next = indexPath.item - 1;
//为了不让next越界,进行取余运算 ---------+next为了切换图片
next = (self.index + kPictureCount + next) % kPictureCount;
NSString * imgName = [NSString stringWithFormat:@"%02ld",next + 1];
UIImage * img = [UIImage imageNamed:imgName];
cell.img = img;
return cell;
}










