溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

發(fā)布時(shí)間:2020-10-24 12:48:49 來源:腳本之家 閱讀:238 作者:zhifenx 欄目:移動(dòng)開發(fā)

最近一直在找實(shí)現(xiàn)圖片無限輪播的方法,在網(wǎng)上也看了不少方法,大都不太合適,最終看到某IT培訓(xùn)公司一位講師用

UICollectionView:一行代碼實(shí)現(xiàn)圖片無限輪播器的方法,當(dāng)然想一行代碼實(shí)現(xiàn)輪播功能,前期還是有一些工作要做。下面就把這個(gè)方法分享給大家!

一、圖片無限輪播實(shí)現(xiàn)效果圖:

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

圖片無限輪播.gif

二、實(shí)現(xiàn)原理與分析:

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

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

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

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

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

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

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

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

Paste_Image.png

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

Paste_Image.png

三、代碼:

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

類文件.png

  •  JFWeakTimerTargetObject繼承自NSObject
  • JFLoopView繼承自UIView
  • JFLoopViewCell繼承自UICollectionViewCell
  • JFLoopViewLayout繼承自UICollectionViewFlowLayout
  • JFMainViewController繼承自UIViewController

JFWeakTimerTargetObject重寫定時(shí)器NSTimer的+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;類方法的目的是:避免當(dāng)定時(shí)器強(qiáng)引用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)建當(dāng)前類對(duì)象
 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;

 //添加分頁(yè)器
 [self addSubview:self.pageControl];

 //回到主線程刷新UI
 dispatch_async(dispatch_get_main_queue(), ^{
 //設(shè)置滾動(dòng)的初始狀態(tài)在
 [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:self.imageArray.count inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];

 //添加定時(shí)器
 [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

/// 滾動(dòng)完畢就會(huì)調(diào)用(如果不是人為拖拽scrollView導(dǎo)致滾動(dòng)完畢,才會(huì)調(diào)用這個(gè)方法)
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
 [self scrollViewDidEndDecelerating:scrollView];
}

/// 當(dāng)滾動(dòng)減速時(shí)調(diào)用
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
 CGFloat offsetX = scrollView.contentOffset.x;
 NSInteger page = offsetX / scrollView.bounds.size.width;

 //手動(dòng)滾動(dòng)到左邊臨界狀態(tài)
 if (page == 0) {
 page = self.imageArray.count;
 self.collectionView.contentOffset = CGPointMake(page * scrollView.frame.size.width, 0);
 //滾動(dòng)到右臨界狀態(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當(dāng)前頁(yè)
 NSInteger currentPage = page % self.imageArray.count;
 self.pageControl.currentPage =currentPage;
 //添加定時(shí)器
 [self addTimer];
}

///手指開始拖動(dòng)時(shí)調(diào)用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
 //移除定時(shí)器
 [self removeTimer];
}

/// 添加定時(shí)器
- (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];
}

/// 移除定時(shí)器
- (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

/// 準(zhǔn)備布局
- (void)prepareLayout {
 [super prepareLayout];

 //設(shè)置item尺寸
 self.itemSize = self.collectionView.frame.size;
 //設(shè)置滾動(dòng)方向
 self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
 //設(shè)置分頁(yè)
 self.collectionView.pagingEnabled = YES;

 //設(shè)置最小間距
 self.minimumLineSpacing = 0;
 self.minimumInteritemSpacing = 0;

 //隱藏水平滾動(dòng)條
 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];

 //關(guān)閉自動(dòng)調(diào)整滾動(dòng)視圖
 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"];

 //此行代碼實(shí)現(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是干嘛的呢?簡(jiǎn)單點(diǎn)說就是automaticallyAdjustsScrollViewInsets根據(jù)所在界面的status bar、navigationbar、與tabbar的高度,自動(dòng)調(diào)整scrollview的 inset,設(shè)置為NO,不讓viewController調(diào)整,我們自己修改布局即可。如果不設(shè)置為NO就可能出現(xiàn)下面的情況,自動(dòng)滾動(dòng)和拖動(dòng)的時(shí)候imageView的位置會(huì)變化。

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器

圖片無限輪播bug展示.gif

四、總結(jié):

1、實(shí)現(xiàn)無限輪播器的主要控件是UICollectionView和UIPageControl,
2、封裝好工具類以后再使用時(shí)一行_loopView = [[JFLoopView alloc] initWithImageArray:imageArray];代碼,然后設(shè)置frame就可以復(fù)用無限輪播器。
3、合理切換圖片和圖片排列的方法,加上恰當(dāng)?shù)厥褂肬ICollectionView提供的代理方法就可以完美的實(shí)現(xiàn)無限輪播器。

寫在最后:

下一篇文章講用UICollectionView實(shí)現(xiàn)電商APP首頁(yè)的方法:

一行iOS代碼實(shí)現(xiàn)圖片無限輪播器
電商APP的首頁(yè)展示.gif

如果你有好的方法敬請(qǐng)分享,感謝你的閱讀!歡迎關(guān)注和評(píng)論!

源碼地址:鏈接: https://pan.baidu.com/s/1nv5FqZJ 密碼: qz3u

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI