一行iOS代碼實現圖片無限輪播器

最近一直在找實現圖片無限輪播的方法,在網上也看了不少方法,大都不太合適,最終看到某IT培訓公司一位講師用

創(chuàng)新互聯(lián)專注于西峰企業(yè)網站建設,響應式網站建設,購物商城網站建設。西峰網站建設公司,為西峰等地區(qū)提供建站服務。全流程按需策劃設計,專業(yè)設計,全程項目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務

UICollectionView:一行代碼實現圖片無限輪播器的方法,當然想一行代碼實現輪播功能,前期還是有一些工作要做。下面就把這個方法分享給大家!

一、圖片無限輪播實現效果圖:

一行iOS代碼實現圖片無限輪播器

圖片無限輪播.gif

二、實現原理與分析:

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

一行iOS代碼實現圖片無限輪播器

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

一行iOS代碼實現圖片無限輪播器

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

一行iOS代碼實現圖片無限輪播器

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

一行iOS代碼實現圖片無限輪播器

Paste_Image.png

一行iOS代碼實現圖片無限輪播器

Paste_Image.png

三、代碼:

一行iOS代碼實現圖片無限輪播器

類文件.png

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

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];
}

@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(), ^{
 //設置滾動的初始狀態(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 數據源方法
- (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;

 //手動滾動到左邊臨界狀態(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);
 }

 //設置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的位置會變化。

一行iOS代碼實現圖片無限輪播器

圖片無限輪播bug展示.gif

四、總結:

1、實現無限輪播器的主要控件是UICollectionView和UIPageControl,
2、封裝好工具類以后再使用時一行_loopView = [[JFLoopView alloc] initWithImageArray:imageArray];代碼,然后設置frame就可以復用無限輪播器。
3、合理切換圖片和圖片排列的方法,加上恰當地使用UICollectionView提供的代理方法就可以完美的實現無限輪播器。

寫在最后:

下一篇文章講用UICollectionView實現電商APP首頁的方法:

一行iOS代碼實現圖片無限輪播器
電商APP的首頁展示.gif

如果你有好的方法敬請分享,感謝你的閱讀!歡迎關注和評論!

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當前文章:一行iOS代碼實現圖片無限輪播器
分享地址:http://muchs.cn/article38/ghscpp.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網站品牌網站設計、App設計服務器托管、、網站內鏈

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

綿陽服務器托管