輪播 顧名思義就是無(wú)限滾動(dòng). 在日常開發(fā)中, 我們經(jīng)常需要對(duì)一些廣告和一些圖片進(jìn)行自動(dòng)的輪播.
一般我們想到的是使用UIScrollView, 上面添加多個(gè)照片, 然后前后各添加一張照片, 實(shí)現(xiàn)無(wú)限滾動(dòng), 這樣做存在一個(gè)問(wèn)題就是, 如果 圖片數(shù)量為三五張完全沒(méi)問(wèn)題, 但是如果有十幾張照片或者瀏覽照片庫(kù)的時(shí)候就不得不考慮性能問(wèn)題, 造成內(nèi)存浪費(fèi)性能低. 所以今天我們用collectionView的重用機(jī)制優(yōu)化內(nèi)存.
實(shí)現(xiàn)過(guò)程:
首先創(chuàng)建collectionView使用collection的flowLayout布局
flowLayout的代碼
.h
#import <UIKit/UIKit.h>
@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中創(chuàng)建圖片
自定義cell的.h
#import <UIKit/UIKit.h>
@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) {
// 在這里創(chuàng)建子控件但是布局要寫到layoutSubviews中
self.imageViewOfItem = [[UIImageView alloc] init];
[self addSubview:_imageViewOfItem];
}
return self;
}
// 子控件的布局
- (void)layoutSubviews {
// 注意父類的調(diào)用
[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中創(chuàng)建collectionView了
#import "ViewController.h"
#import "LayoutFirst.h"
#import "CellForImage.h"
@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate>
@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 ------------ 處理照片的數(shù)組 -----------
- (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];
// 創(chuàng)建collectionView
[self createCollrctionView];
// 創(chuàng)建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;
// 添加定時(shí)器
[self addNSTimer];
}
#pragma mark ------------ 創(chuàng)建collectionView的實(shí)現(xiàn)必須的協(xié)議 -----------
- (void)createCollrctionView {
// flowLayout的初始化可以對(duì)item進(jìn)行設(shè)置: 大小, 以及周邊距
self.flowLayout = [[LayoutFirst alloc] init];
// 創(chuàng)建對(duì)象
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個(gè)數(shù)
- (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;
}
// 這里是返回分區(qū)的個(gè)數(shù)(默認(rèn)為1)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 100;
}
#pragma mark ------------ 添加定時(shí)器 -----------
- (void)addNSTimer {
self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
// 添加到runloop中
[[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
// 定時(shí)器的作用, 下一個(gè)圖
- (void)next {
// 獲取當(dāng)前正在展示的位置
NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
// 反回中間的數(shù)據(jù)100是返回的分區(qū)個(gè)數(shù)
NSIndexPath *currentIndexPathRest = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:100 / 2];
[self.collectionView scrollToItemAtIndexPath:currentIndexPathRest atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
// 計(jì)算出下一個(gè)需要展示的位置
NSInteger nextItem = currentIndexPathRest.item + 1;
NSInteger nextSection = currentIndexPathRest.section;
if (nextItem == self.mArrOfPhoto.count) {
nextItem = 0;
nextSection++;
}
NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
// 通過(guò)動(dòng)畫滾到下一個(gè)位置
[self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
self.page.currentPage = nextItem;
}
#pragma mark ------------ 當(dāng)用戶拖拽的時(shí)候就調(diào)用移除定時(shí) -----------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[self removeNSTimer];
}
- (void)removeNSTimer {
[self.timer invalidate];
self.timer = nil;
}
#pragma mark ------------ 當(dāng)用戶停止拖拽的時(shí)候調(diào)用 -----------
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
[self addNSTimer];
}
#pragma mark ------------ 設(shè)置頁(yè)碼 -----------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
int page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width) % self.mArrOfPhoto.count;
self.page.currentPage = page;
}
這里面主要用到NSTimer的一些簡(jiǎn)單用法和如下這個(gè)方法
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
// 1)谴忧、(NSTimeInterval)ti : 預(yù)訂一個(gè)Timer,設(shè)置一個(gè)時(shí)間間隔帅容。
表示輸入一個(gè)時(shí)間間隔對(duì)象橄务,以秒為單位,一個(gè)>0的浮點(diǎn)類型的值娄昆,如果該值<0,系統(tǒng)會(huì)默認(rèn)為0.1。
// 2)、target:(id)aTarget : 表示發(fā)送的對(duì)象踢步,如self
// 3)、selector:(SEL)aSelector : 方法選擇器丑掺,在時(shí)間間隔內(nèi)获印,選擇調(diào)用一個(gè)實(shí)例方法
// 4)、userInfo:(nullable id)userInfo : 需要傳參街州,可以為nil
// 5)兼丰、repeats:(BOOL)yesOrNo : 當(dāng)YES時(shí),定時(shí)器會(huì)不斷循環(huán)直至失效或被釋放唆缴,當(dāng)NO時(shí)鳍征,定時(shí)器會(huì)循環(huán)發(fā)送一次就失效。
// 開啟定時(shí)器:
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// 關(guān)閉定時(shí)器
[self.timer invalidate];
這種方法實(shí)現(xiàn)的無(wú)限輪播圖有一個(gè)小缺陷, 就不說(shuō)了, 自己慢慢發(fā)現(xiàn)吧.