iOS實現(xiàn)UICollectionViewDataSource與Controller的分離

之前每次用到UICollectionView的時候都會都需要在Controller里面去實現(xiàn)DataSource & Delegate方法

單獨Delegate方法還好不是很多, 但是再加上DataSource就很臃腫了, 為了避免代碼臃腫也減少ViewController的代碼量

我們可以將DataSource方法分離出去, 大致方法如下:

-> 創(chuàng)建需要的Model & 自定義Cell文件

-> 創(chuàng)建DataSource類, 導(dǎo)入 Cell頭文件并實現(xiàn)UICollectionViewDatasource

-> 在Controller中導(dǎo)入Model & DataSource類

-> 創(chuàng)建DataSource類實例, 將數(shù)據(jù)傳入DataSource中

-> 創(chuàng)建UICollectionView, 將CollectionView的datasource指給上面創(chuàng)建的Datasource實例即可

下面舉例示范:

為了簡單 我就只下一個自定義的Cell model就不寫了

ShowPhotoCollectionViewCell.h

#import <UIKit/UIKit.h>

@interface ShowPhotoCollectionViewCell : UICollectionViewCell

@property (nonatomic, strong) UILabel     *lable;
@property (nonatomic, strong) UIImageView *imageView;

/**
 配置Cell方法
 
 @param imageLink 圖片地址
 @param title 標(biāo)題
 */
- (void)configCellWithImageLink:(NSString *)imageLink withTitle:(NSString *)title;
@end

ShowPhotoCollectionViewCell.m

#import "ShowPhotoCollectionViewCell.h"
#import "UIImageView+WebCache.h"
#import "UIImage+Image.h"

@implementation ShowPhotoCollectionViewCell

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    if (self) {
        
        self.lable = ({
            
            UILabel *lable        = [[UILabel alloc] initWithFrame:\
                                     CGRectMake((SCREEN_WIDTH - 40) / 2, 40, 40, 25)];
            
            lable.textAlignment   = NSTextAlignmentCenter;
            lable.font            = [UIFont systemFontOfSize:12];
            lable.backgroundColor = [UIColor blackColor];
            lable.textColor       = [UIColor whiteColor];
            
            lable;
        });
        
        self.imageView = ({
            
            UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(40, 80, SCREEN_WIDTH - 80, SCREEN_HEIGHT - 80 - 80)];
            
            imgView;
        });
        
        [self addSubview:self.lable];
        [self addSubview:self.imageView];
    }
    
    return self;
}

- (void)configCellWithImageLink:(NSString *)imageLink withTitle:(NSString *)title {
    
    self.lable.text = title;
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:imageLink]
                      placeholderImage:[UIImage imageWithColor:[UIColor whiteColor]]];
}

@end

ShowPhotoDataSource.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface ShowPhotoDataSource : NSObject <UICollectionViewDataSource>

@property (nonatomic, strong) NSArray  *imgLinkArray;
@property (nonatomic, strong) NSString *identifier;

/**
 導(dǎo)入外部數(shù)據(jù)
 
 @param linkArray Image地址數(shù)組
 @param identifier cell標(biāo)識
 @return 返回實例
 */
- (id)initWithImageLinkArray:(NSArray *)linkArray withIdentifier:(NSString *)identifier;

/**
 根據(jù)索引返回圖片地址
 
 @param indexPath 索引
 @return 返回圖片地址
 */
- (id)imgLinkAtIndexPath:(NSIndexPath *)indexPath;

@end

ShowPhotoDataSource.m

#import "ShowPhotoDataSource.h"
#import "ShowPhotoCollectionViewCell.h"

@implementation ShowPhotoDataSource

- (id)initWithImageLinkArray:(NSArray *)linkArray withIdentifier:(NSString *)identifier{
    
    self = [super init];
    if (self) {
        
        self.imgLinkArray = linkArray;
        self.identifier   = identifier;
    }
    
    return self;
}

- (id)imgLinkAtIndexPath:(NSIndexPath *)indexPath {
    
    return self.imgLinkArray[indexPath.row];
}

#pragma mark - CollectionView dataSource Methods
- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {
    
    return self.imgLinkArray.count;
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                           cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ShowPhotoCollectionViewCell *cell = \
    [collectionView dequeueReusableCellWithReuseIdentifier:self.identifier
                                              forIndexPath:indexPath];
    [cell configCellWithImageLink:[self imgLinkAtIndexPath:indexPath]
                        withTitle:\
     [NSString stringWithFormat:@"%d/%d", indexPath.row + 1 , self.imgLinkArray.count]];
    
    return cell;
}

@end

下面是在Controller中的使用方法

//創(chuàng)建CollectionView
- (void)createCollectionView {
    
    self.dataSource = ({
        
        PhotoDataSource *dataSource = [[PhotoDataSource alloc] \
                                       initWithImageLinkArray:self.imglinkArray
                                               withIdentifier:PHOTOCELLIDENTIFIER];
        
        dataSource;
    });
    
    self.myCollectionView = ({
    
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        UICollectionView *collection       = [[UICollectionView alloc] initWithFrame:\
                        CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:layout];
        
        [collection registerClass:[PhotoCollectionViewCell class]
                                                    forCellWithReuseIdentifier:PHOTOCELLIDENTIFIER];
        
        collection.showsHorizontalScrollIndicator = NO;
        collection.dataSource                     = self.dataSource;
        collection.delegate                       = self;
        
        collection;
    });
    
    [self.view addSubview:self.myCollectionView];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末瀑罗,一起剝皮案震驚了整個濱河市娃弓,隨后出現(xiàn)的幾起案子之拨,更是在濱河造成了極大的恐慌,老刑警劉巖辑鲤,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異撬陵,居然都是意外死亡拦宣,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進店門垮刹,熙熙樓的掌柜王于貴愁眉苦臉地迎上來达吞,“玉大人,你說我怎么就攤上這事荒典±医伲” “怎么了?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵寺董,是天一觀的道長覆糟。 經(jīng)常有香客問我,道長遮咖,這世上最難降的妖魔是什么滩字? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮御吞,結(jié)果婚禮上麦箍,老公的妹妹穿的比我還像新娘。我一直安慰自己陶珠,他們只是感情好挟裂,可當(dāng)我...
    茶點故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著揍诽,像睡著了一般诀蓉。 火紅的嫁衣襯著肌膚如雪栗竖。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天渠啤,我揣著相機與錄音划滋,去河邊找鬼。 笑死埃篓,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的根资。 我是一名探鬼主播架专,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼玄帕!你這毒婦竟也來了部脚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤裤纹,失蹤者是張志新(化名)和其女友劉穎委刘,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鹰椒,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡锡移,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了漆际。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片淆珊。...
    茶點故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖奸汇,靈堂內(nèi)的尸體忽然破棺而出施符,到底是詐尸還是另有隱情,我是刑警寧澤擂找,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布戳吝,位于F島的核電站,受9級特大地震影響贯涎,放射性物質(zhì)發(fā)生泄漏听哭。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一柬采、第九天 我趴在偏房一處隱蔽的房頂上張望欢唾。 院中可真熱鬧,春花似錦粉捻、人聲如沸礁遣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽祟霍。三九已至杏头,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間沸呐,已是汗流浹背醇王。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留崭添,地道東北人寓娩。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像呼渣,于是被迫代替她去往敵國和親棘伴。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,947評論 2 355

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