圖片輪播器的封裝

版本記錄

版本號(hào) 修改時(shí)間
V1.0 2017.04.18

前言

很多APP都有很多圖片輪播banner直秆,是用戶了解app的重要接口邑狸,也是app發(fā)布活動(dòng)或者消息的很好選擇诡必。比如每年雙11或者其他節(jié)日蒿赢,天貓等app都會(huì)在banner上加入很多活動(dòng)接口润樱,以便用戶盡快獲得活動(dòng)的信息。banner的實(shí)現(xiàn)有很多第三方框架羡棵,我自己封裝了一個(gè)圖片輪播器github壹若,有什么不對(duì)的地方希望大家能給我指出,謝謝皂冰。

詳細(xì)設(shè)計(jì)

我們先看一下代碼組織結(jié)構(gòu)店展。

代碼組織結(jié)構(gòu)

接著看詳細(xì)的代碼

1. AppDelegate.m

#import "AppDelegate.h"
#import "JJBannerVC.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    JJBannerVC *bannerVC = [[JJBannerVC alloc] init];
    self.window.rootViewController = bannerVC;
    [self.window makeKeyAndVisible];
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    
}

@end

2.JJBannerVC.h
#import <UIKit/UIKit.h>

@interface JJBannerVC : UIViewController

@end


3.JJBannerVC.m

#import "JJBannerVC.h"
#import "JJBannerView.h"
#import "Masonry.h"

@interface JJBannerVC ()

@property (nonatomic, strong) JJBannerView *bannerView;


@end

@implementation JJBannerVC

#pragma mark - Override Base Function

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.bannerView = [[JJBannerView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.bannerView];
    
    self.bannerView.imageArr = [self loadImageArr];
    
}

- (void)viewWillLayoutSubviews
{
    [self.bannerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
}

#pragma mark - Object Private Function

- (NSArray *)loadImageArr
{
    NSMutableArray *imageArrM = [NSMutableArray array];
    for (NSInteger i = 0; i < 5; i ++) {
        NSString *imageStr = [NSString stringWithFormat:@"Home_Scroll_%02zd",i+1];
        UIImage *image = [UIImage imageNamed:imageStr];
        [imageArrM addObject:image];
    }
    return imageArrM.copy;
}

@end

4.JJBannerView.h
#import <UIKit/UIKit.h>

@interface JJBannerView : UIView

@property (nonatomic, strong) NSArray *imageArr;

@end


5. JJBannerView.m

#import "JJBannerView.h"
#import "JJBannerFlowLayout.h"
#import "Masonry.h"
#import "JJBannerCollectionViewCell.h"

#define kJJBannerViewSectionCount               (100)

@interface JJBannerView () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation JJBannerView

static NSString * const cellIdentify = @"cellIdentify";

#pragma mark - Overide Base Function

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setupCollectionView];
        [self setupPageControl];
        [self setupTimer];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.offset(-40);
        make.centerX.equalTo(self);
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];

}

- (void)removeFromSuperview
{
    [super removeFromSuperview];
    
    [self.timer invalidate];
}

#pragma mark - Object Private Function

- (void)setupCollectionView
{
    JJBannerFlowLayout *flowLayout = [[JJBannerFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    [self addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[JJBannerCollectionViewCell class] forCellWithReuseIdentifier:cellIdentify];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
}

- (void)setupPageControl
{
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.currentPageIndicatorTintColor = [UIColor darkGrayColor];
    pageControl.pageIndicatorTintColor = [UIColor lightGrayColor];
    [self addSubview:pageControl];
    self.pageControl = pageControl;

}

- (void)setupTimer
{
    self.timer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

}

#pragma mark - Object Base Function

- (void)nextPage
{
    NSInteger page = self.pageControl.currentPage;
    NSIndexPath *scrollIndexPath = nil;
    // 如果是最后一張圖片
    if (page == self.imageArr.count - 1) {
        scrollIndexPath = [NSIndexPath indexPathForItem:0 inSection:kJJBannerViewSectionCount/2 + 1];
    }
    else {
        scrollIndexPath = [NSIndexPath indexPathForItem:page + 1 inSection:kJJBannerViewSectionCount/2];
    }
    [self.collectionView scrollToItemAtIndexPath:scrollIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource>

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    self.timer.fireDate = [NSDate distantFuture];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    self.timer.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / scrollView.bounds.size.width;
    
    NSInteger sectionNum = page / self.imageArr.count;
    NSInteger itemNUm = page % self.imageArr.count;
    
    if (sectionNum == kJJBannerViewSectionCount/2) {
        return;
    }
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForItem:itemNUm inSection:kJJBannerViewSectionCount/2];
    [self.collectionView scrollToItemAtIndexPath:scrollIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    NSInteger page = (scrollView.contentOffset.x/scrollView.bounds.size.width) + 0.499;
    NSInteger pageNO = page % self.imageArr.count;
    self.pageControl.currentPage = pageNO;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return  kJJBannerViewSectionCount;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    JJBannerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentify forIndexPath:indexPath];
    cell.indexPath = indexPath;
    return cell;
}

#pragma mark - Getter & Setter Function

- (void)setImageArr:(NSArray *)imageArr
{
    _imageArr = imageArr;
    
    [self.collectionView reloadData];
    self.pageControl.numberOfPages = self.imageArr.count;
    [self layoutIfNeeded];
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForItem:0 inSection:kJJBannerViewSectionCount/2];
    [self.collectionView scrollToItemAtIndexPath:scrollIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}

@end


6.JJBannerFlowLayout.h

#import <UIKit/UIKit.h>

@interface JJBannerFlowLayout : UICollectionViewFlowLayout

@end

7.JJBannerFlowLayout.m

#import "JJBannerFlowLayout.h"

@implementation JJBannerFlowLayout

- (void)prepareLayout
{
    [super prepareLayout];
    
    self.itemSize = self.collectionView.bounds.size;
    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.minimumLineSpacing = 0;
    self.minimumInteritemSpacing = 0;
}

@end


8.JJBannerCollectionViewCell.h
#import <UIKit/UIKit.h>

@interface JJBannerCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) NSIndexPath *indexPath;

@end


9. JJBannerCollectionViewCell.m
#import "JJBannerCollectionViewCell.h"
#import "Masonry.h"

@interface JJBannerCollectionViewCell ()

@property (nonatomic, strong) UIImageView *imageView;


@end

@implementation JJBannerCollectionViewCell

#pragma mark - Override Base Function

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
    }
    
    return self;

}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];

}

#pragma mark - Object Base Function

- (void)setupUI
{
    UIImageView *imageView = [[UIImageView alloc] init];
    
    [self.contentView addSubview:imageView];
    self.imageView = imageView;

}

#pragma mark - Getter & Setter Function

- (void)setIndexPath:(NSIndexPath *)indexPath
{
    _indexPath = indexPath;
    
    self.imageView.image = [UIImage imageNamed:@(indexPath.item).description];
}

@end

設(shè)計(jì)結(jié)果

我們直接看下邊的gif圖。

設(shè)計(jì)結(jié)果

可以看見實(shí)現(xiàn)了圖片輪播的效果秃流。

后記

這個(gè)東西很簡單赂蕴,但是我還是自己寫了一遍,有些東西很長時(shí)間不寫就忘記不少了舶胀,但是看看還是能很快的撿起來概说,相信大家和我都是一樣的。希望我寫的這個(gè)小東西能對(duì)大家有用嚣伐,再次謝謝大家對(duì)我的支持席怪。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市纤控,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌碉纺,老刑警劉巖船万,帶你破解...
    沈念sama閱讀 212,332評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異骨田,居然都是意外死亡耿导,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,508評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門态贤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來舱呻,“玉大人,你說我怎么就攤上這事悠汽∠渎溃” “怎么了?”我有些...
    開封第一講書人閱讀 157,812評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵柿冲,是天一觀的道長茬高。 經(jīng)常有香客問我,道長假抄,這世上最難降的妖魔是什么怎栽? 我笑而不...
    開封第一講書人閱讀 56,607評(píng)論 1 284
  • 正文 為了忘掉前任丽猬,我火速辦了婚禮,結(jié)果婚禮上熏瞄,老公的妹妹穿的比我還像新娘脚祟。我一直安慰自己,他們只是感情好强饮,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,728評(píng)論 6 386
  • 文/花漫 我一把揭開白布由桌。 她就那樣靜靜地躺著,像睡著了一般胡陪。 火紅的嫁衣襯著肌膚如雪沥寥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,919評(píng)論 1 290
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼惩琉。 笑死盒粮,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的痊远。 我是一名探鬼主播,決...
    沈念sama閱讀 39,071評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼骤星!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起爆哑,我...
    開封第一講書人閱讀 37,802評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤洞难,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后揭朝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體队贱,經(jīng)...
    沈念sama閱讀 44,256評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,576評(píng)論 2 327
  • 正文 我和宋清朗相戀三年潭袱,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了柱嫌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,712評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡屯换,死狀恐怖编丘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情彤悔,我是刑警寧澤嘉抓,帶...
    沈念sama閱讀 34,389評(píng)論 4 332
  • 正文 年R本政府宣布,位于F島的核電站蜗巧,受9級(jí)特大地震影響掌眠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜幕屹,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,032評(píng)論 3 316
  • 文/蒙蒙 一蓝丙、第九天 我趴在偏房一處隱蔽的房頂上張望级遭。 院中可真熱鬧,春花似錦渺尘、人聲如沸挫鸽。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丢郊。三九已至,卻和暖如春医咨,著一層夾襖步出監(jiān)牢的瞬間枫匾,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,026評(píng)論 1 266
  • 我被黑心中介騙來泰國打工拟淮, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留干茉,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 46,473評(píng)論 2 360
  • 正文 我出身青樓很泊,卻偏偏與公主長得像角虫,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子委造,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,606評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容