iOS中的輪播----collectionView

輪播 顧名思義就是無(wú)限滾動(dòng). 在日常開發(fā)中, 我們經(jīng)常需要對(duì)一些廣告和一些圖片進(jìn)行自動(dòng)的輪播.
一般我們想到的是使用UIScrollView, 上面添加多個(gè)照片, 然后前后各添加一張照片, 實(shí)現(xiàn)無(wú)限滾動(dòng), 這樣做存在一個(gè)問(wèn)題就是, 如果 圖片數(shù)量為三五張完全沒(méi)問(wèn)題, 但是如果有十幾張照片或者瀏覽照片庫(kù)的時(shí)候就不得不考慮性能問(wèn)題, 造成內(nèi)存浪費(fèi)性能低. 所以今天我們用collectionView的重用機(jī)制優(yōu)化內(nèi)存.

實(shí)現(xiàn)過(guò)程:
首先創(chuàng)建collectionView使用collection的flowLayout布局
flowLayout的代碼
.h

#import <UIKit/UIKit.h>

@interface LayoutFirst : UICollectionViewFlowLayout

@end

.m

#import "LayoutFirst.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width


@implementation LayoutFirst

- (instancetype)init {
    self = [super init];
    if (self) {
        // item size
        self.itemSize = CGSizeMake(WIDTH,  300);
        self.minimumLineSpacing = 0;
        self.minimumInteritemSpacing = 0;
//        self.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}
@end

還要自定義cell 在cell中創(chuàng)建圖片
自定義cell的.h

#import <UIKit/UIKit.h>
@interface CellForImage : UICollectionViewCell
@property (nonatomic, copy) NSString *string;
@end

.m

#import "CellForImage.h"
@interface CellForImage ()
@property (nonatomic, strong) UIImageView *imageViewOfItem;
@end
@implementation CellForImage
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
// 在這里創(chuàng)建子控件但是布局要寫到layoutSubviews中
        self.imageViewOfItem = [[UIImageView alloc] init];
        [self addSubview:_imageViewOfItem];
    }
    return self;
}
// 子控件的布局
- (void)layoutSubviews {
// 注意父類的調(diào)用
    [super layoutSubviews];
    self.imageViewOfItem.frame = self.bounds;
    self.imageViewOfItem.backgroundColor = [UIColor cyanColor];
}
// cell中照片的setter方法string是照片的name
- (void)setString:(NSString *)string {
    _string = [string copy];
    self.imageViewOfItem.image = [UIImage imageNamed:string];
}
@end

寫完上述布局就可以在VC中創(chuàng)建collectionView了

#import "ViewController.h"
#import "LayoutFirst.h"
#import "CellForImage.h"

@interface ViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) LayoutFirst *flowLayout;

@property (nonatomic, strong) NSMutableArray *mArrOfPhoto;

@property (nonatomic, strong) UIPageControl *page;

@property (nonatomic, strong) NSTimer *timer;
@end

@implementation ViewController

#pragma mark ------------ 處理照片的數(shù)組  -----------
- (NSArray *)arrayOfPhoto {

    if (_mArrOfPhoto == nil) {
        
        _mArrOfPhoto = [NSMutableArray array];
        for (int i = 1; i < 11; i++) {
            
            NSString *photoName = [NSString stringWithFormat:@"%d", i];
            [_mArrOfPhoto addObject:photoName];
        }
    }
    return _mArrOfPhoto;   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.navigationController.navigationBar.translucent = NO;
    [self arrayOfPhoto];
// 創(chuàng)建collectionView
    [self createCollrctionView];
    // 創(chuàng)建pageControl
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(150, 270, self.view.bounds.size.width - 300, 20)];
    [self.view addSubview:self.page];
    self.page.numberOfPages = self.mArrOfPhoto.count;
    // 添加定時(shí)器
    [self addNSTimer];
}
#pragma mark ------------  創(chuàng)建collectionView的實(shí)現(xiàn)必須的協(xié)議  -----------
- (void)createCollrctionView {
  // flowLayout的初始化可以對(duì)item進(jìn)行設(shè)置: 大小, 以及周邊距
    self.flowLayout = [[LayoutFirst alloc] init];
    // 創(chuàng)建對(duì)象
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 300) collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self.collectionView registerClass:[CellForImage class] forCellWithReuseIdentifier:@"pool"];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:50] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
}
// 返回item個(gè)數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return _mArrOfPhoto.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    CellForImage *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"pool" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor redColor];
    cell.string = _mArrOfPhoto[indexPath.item];
    return cell;
}
// 這里是返回分區(qū)的個(gè)數(shù)(默認(rèn)為1)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 100;
}
#pragma mark ------------  添加定時(shí)器  -----------
- (void)addNSTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(next) userInfo:nil repeats:YES];
    // 添加到runloop中
    [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
// 定時(shí)器的作用, 下一個(gè)圖
- (void)next {
    // 獲取當(dāng)前正在展示的位置
    NSIndexPath *currentIndexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
// 反回中間的數(shù)據(jù)100是返回的分區(qū)個(gè)數(shù)
    NSIndexPath *currentIndexPathRest = [NSIndexPath indexPathForItem:currentIndexPath.item inSection:100 / 2];
    [self.collectionView scrollToItemAtIndexPath:currentIndexPathRest atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    // 計(jì)算出下一個(gè)需要展示的位置
    NSInteger nextItem = currentIndexPathRest.item + 1;
    NSInteger nextSection = currentIndexPathRest.section;
    if (nextItem == self.mArrOfPhoto.count) {   
        nextItem = 0;
        nextSection++;
    }
    NSIndexPath *nextIndexPath = [NSIndexPath indexPathForItem:nextItem inSection:nextSection];
    // 通過(guò)動(dòng)畫滾到下一個(gè)位置
    [self.collectionView scrollToItemAtIndexPath:nextIndexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
    self.page.currentPage = nextItem;
}
#pragma mark ------------  當(dāng)用戶拖拽的時(shí)候就調(diào)用移除定時(shí)  -----------
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self removeNSTimer];
}
- (void)removeNSTimer {
    [self.timer invalidate];
    self.timer = nil;
}
#pragma mark ------------  當(dāng)用戶停止拖拽的時(shí)候調(diào)用  -----------
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self addNSTimer];
}
#pragma mark ------------  設(shè)置頁(yè)碼  -----------
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int page = (int)(scrollView.contentOffset.x / scrollView.frame.size.width) % self.mArrOfPhoto.count;
    self.page.currentPage = page;
}

這里面主要用到NSTimer的一些簡(jiǎn)單用法和如下這個(gè)方法

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;

// 1)谴忧、(NSTimeInterval)ti : 預(yù)訂一個(gè)Timer,設(shè)置一個(gè)時(shí)間間隔帅容。 
表示輸入一個(gè)時(shí)間間隔對(duì)象橄务,以秒為單位,一個(gè)>0的浮點(diǎn)類型的值娄昆,如果該值<0,系統(tǒng)會(huì)默認(rèn)為0.1。
// 2)、target:(id)aTarget : 表示發(fā)送的對(duì)象踢步,如self
// 3)、selector:(SEL)aSelector : 方法選擇器丑掺,在時(shí)間間隔內(nèi)获印,選擇調(diào)用一個(gè)實(shí)例方法
// 4)、userInfo:(nullable id)userInfo : 需要傳參街州,可以為nil
// 5)兼丰、repeats:(BOOL)yesOrNo : 當(dāng)YES時(shí),定時(shí)器會(huì)不斷循環(huán)直至失效或被釋放唆缴,當(dāng)NO時(shí)鳍征,定時(shí)器會(huì)循環(huán)發(fā)送一次就失效。
// 開啟定時(shí)器:
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
// 關(guān)閉定時(shí)器
[self.timer invalidate];

這種方法實(shí)現(xiàn)的無(wú)限輪播圖有一個(gè)小缺陷, 就不說(shuō)了, 自己慢慢發(fā)現(xiàn)吧.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末琐谤,一起剝皮案震驚了整個(gè)濱河市蟆技,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌斗忌,老刑警劉巖质礼,帶你破解...
    沈念sama閱讀 222,590評(píng)論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異织阳,居然都是意外死亡眶蕉,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門唧躲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)造挽,“玉大人碱璃,你說(shuō)我怎么就攤上這事》谷耄” “怎么了嵌器?”我有些...
    開封第一講書人閱讀 169,301評(píng)論 0 362
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)谐丢。 經(jīng)常有香客問(wèn)我爽航,道長(zhǎng),這世上最難降的妖魔是什么乾忱? 我笑而不...
    開封第一講書人閱讀 60,078評(píng)論 1 300
  • 正文 為了忘掉前任讥珍,我火速辦了婚禮,結(jié)果婚禮上窄瘟,老公的妹妹穿的比我還像新娘衷佃。我一直安慰自己,他們只是感情好蹄葱,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,082評(píng)論 6 398
  • 文/花漫 我一把揭開白布氏义。 她就那樣靜靜地躺著,像睡著了一般新蟆。 火紅的嫁衣襯著肌膚如雪觅赊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,682評(píng)論 1 312
  • 那天琼稻,我揣著相機(jī)與錄音吮螺,去河邊找鬼。 笑死帕翻,一個(gè)胖子當(dāng)著我的面吹牛鸠补,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播嘀掸,決...
    沈念sama閱讀 41,155評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼紫岩,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了睬塌?” 一聲冷哼從身側(cè)響起泉蝌,我...
    開封第一講書人閱讀 40,098評(píng)論 0 277
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎揩晴,沒(méi)想到半個(gè)月后勋陪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,638評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡硫兰,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,701評(píng)論 3 342
  • 正文 我和宋清朗相戀三年诅愚,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片劫映。...
    茶點(diǎn)故事閱讀 40,852評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡违孝,死狀恐怖刹前,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情雌桑,我是刑警寧澤喇喉,帶...
    沈念sama閱讀 36,520評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站筹燕,受9級(jí)特大地震影響轧飞,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜撒踪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,181評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望大渤。 院中可真熱鬧制妄,春花似錦、人聲如沸泵三。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)烫幕。三九已至俺抽,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間较曼,已是汗流浹背磷斧。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評(píng)論 1 274
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留捷犹,地道東北人弛饭。 一個(gè)月前我還...
    沈念sama閱讀 49,279評(píng)論 3 379
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像萍歉,于是被迫代替她去往敵國(guó)和親侣颂。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,851評(píng)論 2 361

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)枪孩、插件憔晒、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,124評(píng)論 4 61
  • ZZNewsSheetMenu 關(guān)鍵詞 UIScrollView,UILongPressGestureRecogn...
    Colleny_Z閱讀 2,084評(píng)論 0 2
  • 最近蔑舞,莫名其妙的被很多人加微信拒担,開場(chǎng)白無(wú)一例外:“聽說(shuō)你用兩個(gè)月,跨專業(yè)考上了中傳的研究生斗幼,我也想考研澎蛛,想取取經(jīng)…...
    諾芷汐閱讀 1,727評(píng)論 23 32
  • 過(guò)去的十年都是開車出行,四月開始我常常擠地鐵蜕窿,甚至追過(guò)末班車…… 四月的忙碌谋逻,讓我充實(shí)的找不著北呆馁,地鐵上的...
    英兒少爺閱讀 165評(píng)論 0 0
  • 筆記:委身喜樂(lè)便是委身于摧毀喜樂(lè)的每一個(gè)仇敵。殲滅敵人卻留下一個(gè)活口是不夠的毁兆,有個(gè)仇敵還屹立不搖浙滤,不但沒(méi)有受到挑戰(zhàn)...
    玲瓏_0533閱讀 356評(píng)論 0 1