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

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

初始界狀態.png

右臨界狀態.png

左臨界狀態.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 {
//創建當前類對象
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];
}
@end
JFLoopView.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;
@end
static 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(), ^{
//設置滾動的初始狀態在
[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 數據源方法
- (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
/// 滾動完畢就會調用(如果不是人為拖拽scrollView導致滾動完畢,才會調用這個方法)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
[self scrollViewDidEndDecelerating:scrollView];
}
/// 當滾動減速時調用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
CGFloat offsetX = scrollView.contentOffset.x;
NSInteger page = offsetX / scrollView.bounds.size.width;
//手動滾動到左邊臨界狀態
if (page == 0) {
page = self.imageArray.count;
self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0);
//滾動到右臨界狀態
}else if (page == [self.collectionView numberOfItemsInSection:0] - 1) {
page = self.imageArray.count - 1;
self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0);
}
//設置UIPageControl當前頁
NSInteger currentPage = page % self.imageArray.count;
self.pageControl.currentPage =currentPage;
//添加定時器
[self addTimer];
}
///手指開始拖動時調用
- (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];
}
@end
JFLoopViewCell.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;
}
@end
JFLoopViewLayout.h文件
#import <UIKit/UIKit.h> @interface JFLoopViewLayout : UICollectionViewFlowLayout @end
JFLoopViewLayout.m文件
#import "JFLoopViewLayout.h"
@implementation JFLoopViewLayout
/// 準備布局
- (void)prepareLayout {
[super prepareLayout];
//設置item尺寸
self.itemSize = self.collectionView.frame.size;
//設置滾動方向
self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//設置分頁
self.collectionView.pagingEnabled = YES;
//設置最小間距
self.minimumLineSpacing = 0;
self.minimumInteritemSpacing = 0;
//隱藏水平滾動條
self.collectionView.showsHorizontalScrollIndicator = NO;
}
@end
JFMainViewController.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];
//關閉自動調整滾動視圖
self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
self.navigationController.navigationBar.hidden = YES;
}
- (void)loadView {
[super loadView];
//設置圖片數據
NSArray *imageArray = @[@"srcoll_01",@"srcoll_02",@"srcoll_03"];
//此行代碼實現無限輪播
_loopView = [[JFLoopView alloc] initWithImageArray:imageArray];
//設置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,一定要記得設置self.automaticallyAdjustsScrollViewInsets = NO; automaticallyAdjustsScrollViewInsets是干嘛的呢?簡單點說就是automaticallyAdjustsScrollViewInsets根據所在界面的status bar、navigationbar、與tabbar的高度,自動調整scrollview的 inset,設置為NO,不讓viewController調整,我們自己修改布局即可。如果不設置為NO就可能出現下面的情況,自動滾動和拖動的時候imageView的位置會變化。

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

電商APP的首頁展示.gif
如果你有好的方法敬請分享,感謝你的閱讀!歡迎關注和評論!
源碼地址:鏈接: https://pan.baidu.com/s/1nv5FqZJ 密碼: qz3u
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。