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

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

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

圖片無(wú)限輪播.gif

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

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

初始界狀態(tài).png
右臨界狀態(tài).png
左臨界狀態(tài).png
Paste_Image.png
Paste_Image.png

三、代碼:

類文件.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無(wú)法被釋放的問(wèn)題。
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)無(wú)限輪播
    _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)說(shuō)就是automaticallyAdjustsScrollViewInsets根據(jù)所在界面的status bar、navigationbar、與tabbar的高度,自動(dòng)調(diào)整scrollviewinset,設(shè)置為NO,不讓viewController調(diào)整,我們自己修改布局即可。如果不設(shè)置為NO就可能出現(xiàn)下面的情況,自動(dòng)滾動(dòng)和拖動(dòng)的時(shí)候imageView的位置會(huì)變化。

圖片無(wú)限輪播bug展示.gif

四、總結(jié):

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

寫在最后:

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


電商APP的首頁(yè)展示.gif

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,029評(píng)論 4 61
  • Bg:圖片輪播器數(shù)不勝數(shù),但大多是UIScrollView + OC實(shí)現(xiàn)的,心血來(lái)潮,決定用Swift+UICol...
    星辰大海_王閱讀 3,394評(píng)論 3 10
  • swift:無(wú)限圖片輪播器 圖片輪播器用處很廣,什么廣告投放呀,新聞?lì)^條滾動(dòng)之類的,都是使用它。出于學(xué)習(xí)的目的用s...
    瘋狂的剁椒魚頭閱讀 7,368評(píng)論 22 27
  • 若要使程序中的jmp指令執(zhí)行后,CS:IP指向程序的第一條指令,在data段中應(yīng)該定義哪些數(shù)據(jù)? 要使jmp指令執(zhí)...
    Cichar閱讀 3,437評(píng)論 0 1
  • 文/一土 將來(lái),在不久的將來(lái)。我會(huì)回想起現(xiàn)在的決定,會(huì)微笑。也許我不會(huì)四十五度角仰望天空,或許會(huì)低頭看看腳下,踩了...
    雨下撒哈拉閱讀 512評(píng)論 2 3

友情鏈接更多精彩內(nèi)容