最近一直在找實現(xiàn)圖片無限輪播的方法,在網(wǎng)上也看了不少方法,大都不太合適,最終看到某IT培訓公司一位講師用
UICollectionView:一行代碼實現(xiàn)圖片無限輪播器的方法,當然想一行代碼實現(xiàn)輪播功能,前期還是有一些工作要做。下面就把這個方法分享給大家!
一、圖片無限輪播實現(xiàn)效果圖:

圖片無限輪播.gif
二、實現(xiàn)原理與分析:
假設(shè)有三張圖片0、1、2,想要實現(xiàn)無限輪播,我們可以將UICollectionView的cell個數(shù)設(shè)為圖片的個數(shù) x 3,也就是把三張圖片重復(fù)添加到9個cell中,可以把無限輪播分解成五種特殊的狀態(tài)(五個臨界點),輪播開始時為初始狀態(tài),在定時器的作用下依次滾動到最后一個cell,此時為右臨界狀態(tài)顯示的是第2張圖片,若想繼續(xù)無縫滾動到第0圖片,我們可以偷偷的將collectionView滾動到第三個cell上,可以看第四幅轉(zhuǎn)態(tài)圖此時顯示的依然是第2張圖片,這樣再次滾動就是第0張圖,這樣就實現(xiàn)了cell向左滾動的無限循環(huán)輪播;向右滾動的原理一樣,就是第三幅圖到第五幅圖的變化。

初始界狀態(tài).png

右臨界狀態(tài).png

左臨界狀態(tài).png

Paste_Image.png

Paste_Image.png
三、代碼:

類文件.png
JFWeakTimerTargetObject重寫定時器NSTimer的+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;類方法的目的是:避免當定時器強引用JFLoopView類,JFLoopView無法被釋放的問題。
JFWeakTimerTargetObject.h文件
#import <Foundation/Foundation.h>@interface JFWeakTimerTargetObject : NSObject+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;@end
JFWeakTimerTargetObject.m文件
#import "JFWeakTimerTargetObject.h"@interface JFWeakTimerTargetObject ()@property (nonatomic, weak) id target;@property (nonatomic, assign) SEL selector;@end@implementation JFWeakTimerTargetObject+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo { //創(chuàng)建當前類對象 JFWeakTimerTargetObject *object = [[JFWeakTimerTargetObject alloc] init]; object.target = aTarget; object.selector = aSelector; return [NSTimer scheduledTimerWithTimeInterval:ti target:object selector:@selector(fire:) userInfo:userInfo repeats:yesOrNo];}- (void)fire:(id)obj { [self.target performSelector:self.selector withObject:obj];}@endJFLoopView.h文件
#import <UIKit/UIKit.h>@interface JFLoopView : UIView//JFLoopView初始化方法- (instancetype)initWithImageArray:(NSArray *)imageArray;@end
JFLoopView.m文件
#import "JFLoopView.h"#import "JFLoopViewLayout.h"#import "JFLoopViewCell.h"#import "JFWeakTimerTargetObject.h"@interface JFLoopView () <UICollectionViewDelegate, UICollectionViewDataSource>@property (nonatomic, strong) UICollectionView *collectionView;@property (nonatomic, strong) UIPageControl *pageControl;@property (nonatomic, strong) NSArray *imageArray;@property (nonatomic, weak) NSTimer *timer;@endstatic NSString *ID = @"loopViewCell";@implementation JFLoopView- (instancetype)initWithImageArray:(NSArray *)imageArray { if (self = [super init]) { UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[JFLoopViewLayout alloc] init]]; [collectionView registerClass:[JFLoopViewCell class] forCellWithReuseIdentifier:ID]; collectionView.dataSource = self; collectionView.delegate = self; [self addSubview:collectionView]; self.collectionView = collectionView; self.imageArray = imageArray; //添加分頁器 [self addSubview:self.pageControl]; //回到主線程刷新UI dispatch_async(dispatch_get_main_queue(), ^{ //設(shè)置滾動的初始狀態(tài)在 [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.imageArray.count inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO]; //添加定時器 [self addTimer]; }); } return self;}/// 懶加載pageControl- (UIPageControl *)pageControl { if (!_pageControl) { _pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 220, 0, 30)]; _pageControl.numberOfPages = self.imageArray.count; _pageControl.pageIndicatorTintColor = [UIColor orangeColor]; _pageControl.currentPageIndicatorTintColor = [UIColor purpleColor]; } return _pageControl;}#pragma mark --- UICollectionViewDataSource 數(shù)據(jù)源方法- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return self.imageArray.count * 3;}- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { JFLoopViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath]; cell.imageName = self.imageArray[indexPath.item % self.imageArray.count]; return cell;}#pragma mark ---- UICollectionViewDelegate/// 滾動完畢就會調(diào)用(如果不是人為拖拽scrollView導(dǎo)致滾動完畢,才會調(diào)用這個方法)- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView { [self scrollViewDidEndDecelerating:scrollView];}/// 當滾動減速時調(diào)用- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView { CGFloat offsetX = scrollView.contentOffset.x; NSInteger page = offsetX / scrollView.bounds.size.width; //手動滾動到左邊臨界狀態(tài) if (page == 0) { page = self.imageArray.count; self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0); //滾動到右臨界狀態(tài) }else if (page == [self.collectionView numberOfItemsInSection:0] - 1) { page = self.imageArray.count - 1; self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0); } //設(shè)置UIPageControl當前頁 NSInteger currentPage = page % self.imageArray.count; self.pageControl.currentPage =currentPage; //添加定時器 [self addTimer];}///手指開始拖動時調(diào)用- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView { //移除定時器 [self removeTimer];}/// 添加定時器- (void)addTimer { if (self.timer) return; self.timer = [JFWeakTimerTargetObject scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(nextImage) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];}/// 移除定時器- (void)removeTimer { [self.timer invalidate]; self.timer = nil;}/// 切換到下一張圖片- (void)nextImage { CGFloat offsetX = self.collectionView.contentOffset.x; NSInteger page = offsetX / self.collectionView.bounds.size.width; [self.collectionView setContentOffset:CGPointMake((page + 1) * self.collectionView.bounds.size.width, 0) animated:YES];}- (void)layoutSubviews { [super layoutSubviews]; self.collectionView.frame = self.bounds;}- (void)dealloc { [self removeTimer];}@endJFLoopViewCell.h文件
#import <UIKit/UIKit.h>@interface JFLoopViewCell : UICollectionViewCell@property (nonatomic, copy) NSString *imageName;@end
JFLoopViewCell.m文件
#import "JFLoopViewCell.h"@interface JFLoopViewCell ()@property (nonatomic, weak) UIImageView *iconView;@end@implementation JFLoopViewCell- (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { UIImageView *iconView = [[UIImageView alloc] init]; [self addSubview:iconView]; self.iconView = iconView; } return self;}- (void)setImageName:(NSString *)imageName { _imageName = imageName; self.iconView.image = [UIImage imageNamed:imageName];}- (void)layoutSubviews { [super layoutSubviews]; self.iconView.frame = self.bounds;}@endJFLoopViewLayout.h文件
#import <UIKit/UIKit.h>@interface JFLoopViewLayout : UICollectionViewFlowLayout@end
JFLoopViewLayout.m文件
#import "JFLoopViewLayout.h"@implementation JFLoopViewLayout/// 準備布局- (void)prepareLayout { [super prepareLayout]; //設(shè)置item尺寸 self.itemSize = self.collectionView.frame.size; //設(shè)置滾動方向 self.scrollDirection = UICollectionViewScrollDirectionHorizontal; //設(shè)置分頁 self.collectionView.pagingEnabled = YES; //設(shè)置最小間距 self.minimumLineSpacing = 0; self.minimumInteritemSpacing = 0; //隱藏水平滾動條 self.collectionView.showsHorizontalScrollIndicator = NO;}@endJFMainViewController.h文件
#import <UIKit/UIKit.h>@interface JFMainViewController : UIViewController@end
JFMainViewController.m文件
#import "JFMainViewController.h"#import "JFLoopView.h"@interface JFMainViewController ()@property (nonatomic, strong) JFLoopView *loopView;@end@implementation JFMainViewController- (void)viewDidLoad { [super viewDidLoad]; //關(guān)閉自動調(diào)整滾動視圖 self.automaticallyAdjustsScrollViewInsets = NO;}- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.navigationController.navigationBar.hidden = YES;}- (void)loadView { [super loadView]; //設(shè)置圖片數(shù)據(jù) NSArray *imageArray = @[@"srcoll_01",@"srcoll_02",@"srcoll_03"]; //此行代碼實現(xiàn)無限輪播 _loopView = [[JFLoopView alloc] initWithImageArray:imageArray]; //設(shè)置loopView的frame _loopView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 250); [self.view addSubview:self.loopView];}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}@end注意:如果你的控制器有UINavigationBar,且隱藏了navigationBar,一定要記得設(shè)置self.automaticallyAdjustsScrollViewInsets = NO; automaticallyAdjustsScrollViewInsets是干嘛的呢?簡單點說就是automaticallyAdjustsScrollViewInsets根據(jù)所在界面的status bar、navigationbar、與tabbar的高度,自動調(diào)整scrollview的 inset,設(shè)置為NO,不讓viewController調(diào)整,我們自己修改布局即可。如果不設(shè)置為NO就可能出現(xiàn)下面的情況,自動滾動和拖動的時候imageView的位置會變化。

圖片無限輪播bug展示.gif
四、總結(jié):
1、實現(xiàn)無限輪播器的主要控件是UICollectionView和UIPageControl,
2、封裝好工具類以后再使用時一行_loopView = [[JFLoopView alloc] initWithImageArray:imageArray];代碼,然后設(shè)置frame就可以復(fù)用無限輪播器。
3、合理切換圖片和圖片排列的方法,加上恰當?shù)厥褂肬ICollectionView提供的代理方法就可以完美的實現(xiàn)無限輪播器。
寫在最后:
下一篇文章講用UICollectionView實現(xiàn)電商APP首頁的方法:

電商APP的首頁展示.gif
如果你有好的方法敬請分享,感謝你的閱讀!歡迎關(guān)注和評論!
源碼地址:鏈接: https://pan.baidu.com/s/1nv5FqZJ 密碼: qz3u
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選