iOS 分組的CollectionView

根據(jù)字?jǐn)?shù)分別設(shè)置兩組數(shù)據(jù)cell的寬度

寫一個#import "HeaderView.h"類繼承于UICollectionReusableView
#import <UIKit/UIKit.h>

@interface HeaderView : UICollectionReusableView
/** titleLabel */
@property (nonatomic,strong) UILabel *titleLabel;
@end

#import "HeaderView.h"

@implementation HeaderView

-(UILabel *)titleLabel{
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 50, 20)];
        _titleLabel.textColor = [UIColor greenColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    
}
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{

    [self addSubview:self.titleLabel];
    
}
同理再寫一個寫一個#import "FooterView.h"類繼承于UICollectionReusableView
#import <UIKit/UIKit.h>

@interface FooterView : UICollectionReusableView
/** titleLabel */
@property (nonatomic,strong) UILabel *titleLabel;
@end

#import "FooterView.h"

@implementation FooterView

-(UILabel *)titleLabel{
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 50, 20)];
        _titleLabel.textColor = [UIColor greenColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    
}
- (void)applyLayoutAttributes:(UICollectionViewLayoutAttributes *)layoutAttributes{

    [self addSubview:self.titleLabel];
    
}
在ViewController里面寫上相應(yīng)代碼
#import "ViewController.h"
#import "HeaderView.h"
#import "FooterView.h"
#import "CollectionViewCell.h"
#define SCREEN_WIDTH ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.width/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.width)
#define SCREENH_HEIGHT ([[UIScreen mainScreen] respondsToSelector:@selector(nativeBounds)]?[UIScreen mainScreen].nativeBounds.size.height/[UIScreen mainScreen].nativeScale:[UIScreen mainScreen].bounds.size.height)
#ifdef DEBUG // 開發(fā)階段-DEBUG階段:使用Log
#define NSLog(FORMAT, ...) fprintf(stderr,"%s:%d\t%s\n",[[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else // 發(fā)布階段-上線階段:移除Log
#define NSLog(FORMAT, ...) nil
#endif

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

/** shuzu */
@property (nonatomic,strong) NSArray *stringArray1;
/** shuzu */
@property (nonatomic,strong) NSArray *stringArray2;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UICollectionViewFlowLayout *collectionViewFlowLayout;
@end

@implementation ViewController
-(UICollectionView *)collectionView{
    if (_collectionView==nil) {
        _collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc]init];
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREENH_HEIGHT-20) collectionViewLayout:self.collectionViewFlowLayout];
        _collectionView.delegate = self;// 設(shè)置代理
        _collectionView.dataSource = self; // 設(shè)置數(shù)據(jù)源代理
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor colorWithRed:239/255.0f green:237/255.0f blue:237/255.0f alpha:1] ; // 設(shè)置背景
        // 注冊cell的類型
        // 以代碼的方式注冊Cell的類型, 表示創(chuàng)建Cell的時候用這個類型來創(chuàng)建
        /*
         第一個參數(shù): Cell的類型
         第二個參數(shù): 重用標(biāo)志
         */
//        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"channelID"];
        [_collectionView registerNib:[UINib nibWithNibName:@"CollectionViewCell" bundle:[NSBundle mainBundle]] forCellWithReuseIdentifier:@"channelID"];
        // 3. 橫向間距
        _collectionViewFlowLayout.minimumInteritemSpacing = 5;
        // 4. 縱向間距
        _collectionViewFlowLayout.minimumLineSpacing = 10;
        
        
        
        //新建headerView類, 繼承自UICollectionReusableView
        //注冊header
        /*
         第一個參數(shù):header視圖對象的類型
         第二個參數(shù):區(qū)分是header還是后面的footer
         // UICollectionElementKindSectionHeader表示header類型
         第三個參數(shù):重用標(biāo)志
         */
        [_collectionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
//
//        //新建FooterView類, 繼承自UICollectionReusableView
//        //注冊footer
        [_collectionView registerClass:[FooterView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    }
    return _collectionView;
}
- (NSArray *)stringArray1{
    if (_stringArray1 == nil) {
        _stringArray1 = @[@"第一個參數(shù)",@"第一數(shù)新類一個參數(shù)",@"參數(shù)",@"第一個參數(shù)View類一個參數(shù)",@"第一個參數(shù)",@"建Fw類",@"第",@"第",@"第一個參數(shù)",@"第w類",@"第一個參數(shù)",@"第一個參數(shù)新ew類"];
    }
    return _stringArray1;
}
- (NSArray *)stringArray2{
    if (_stringArray2 == nil) {
        _stringArray2 = @[@"header視圖",@"繼承iew",@"heade類型",@"繼承自UIC",@"head的類型",@"繼承自ableView",@"heade",@"繼承",@"header視",@"繼承自UICw",@"head",@"繼承自"];
    }
    return _stringArray2;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.collectionView];
    
    
    
    
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray* attributes = [[self.collectionViewFlowLayout layoutAttributesForElementsInRect:rect] mutableCopy];
    
    
    for (UICollectionViewLayoutAttributes *attr in attributes) {
        NSLog(@"%@", NSStringFromCGRect([attr frame]));
    }
    //從第二個循環(huán)到最后一個
    for(int i = 1; i < [attributes count]; ++i) {
        //當(dāng)前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一個attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //我們想設(shè)置的最大間距放妈,可根據(jù)需要改
        NSInteger maximumSpacing = 0;
        //前一個cell的最右邊
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        //如果當(dāng)前一個cell的最右邊加上我們想要的間距加上當(dāng)前cell的寬度依然在contentSize中柳恐,我們改變當(dāng)前cell的原點位置
        //不加這個判斷的后果是逆趣,UICollectionView只顯示一行,原因是下面所有cell的x值都被加到第一行最后一個元素的后面了
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewFlowLayout.collectionViewContentSize.width) {
            CGRect frame = currentLayoutAttributes.frame;
            frame.origin.x = origin + maximumSpacing;
            currentLayoutAttributes.frame = frame;
        }
    }
    
    return attributes;
}
#pragma mark - 遵守協(xié)議, 實現(xiàn)協(xié)議方法
/*
 // 返回每一個Cell的對象
 // UICollectionView上面的每一個Cell是UICollectionViewCell類型(或子類型)的對象
 // UICollectionViewCell也是一個視圖
 */
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    // 從重用隊列里面獲取
    /*
     第一個參數(shù): 重用id
     第二個參數(shù): cell的位置
     */
    
    // UITableView      -> NSIndexPath:section row
    // UICollectionView -> NSIndexPath:section item
    CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"channelID" forIndexPath:indexPath];
    
    // 不需要再創(chuàng)建, 從dequeueReusableCellWithReuseIdentifier方法李米娜一定能夠獲取到
    // 設(shè)置背景顏色
    cell.backgroundColor = [UIColor lightGrayColor];
    cell.titlelabel.text = [NSString stringWithFormat:@"%@",indexPath.section ==0?self.stringArray1[indexPath.row]:self.stringArray2[indexPath.row]];
    cell.titlelabel.font = [UIFont fontWithName:@"HelveticaNeue" size:10.0f];
    cell.titlelabel.textColor = [UIColor whiteColor];
    cell.layer.masksToBounds = YES;
    cell.layer.cornerRadius = 15;
    return cell;
    
}
#pragma mark - 在布局對象的代理協(xié)議方法中設(shè)置header的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 40);
}
#pragma mark - 在布局對象的代理協(xié)議方法中設(shè)置footer的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    return CGSizeMake(SCREEN_WIDTH, 0);
}
#pragma mark - 返回header對象 UICollectionViewDataSource的協(xié)議方法(也可以用來返回footer對象)
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        // header類型
        
        // 從重用隊列里面獲取
        HeaderView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        
        // 設(shè)置背景顏色
        header.backgroundColor = [UIColor redColor];
        
//        [header addSubview:header.titleLabel];
        // 顯示數(shù)據(jù)
        header.titleLabel.text = [NSString stringWithFormat:@"第%c組", (int)(indexPath.section + 'A')];
        return header;
        
    } else if (kind == UICollectionElementKindSectionFooter) {
        // footer
        
//         從重用隊列里面獲取
        FooterView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        
        footer.backgroundColor = [UIColor purpleColor];
        // 顯示數(shù)據(jù)
        footer.titleLabel.text = [NSString stringWithFormat:@"第%c組結(jié)束", (int)(indexPath.section + 'A')];
        return footer;
    }
    return nil;
}
//#pragma mark - UICollectionViewDelegate methods
- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return section==0?self.stringArray1.count:self.stringArray2.count;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    // 3.設(shè)置整個collectionView的內(nèi)邊距
    CGFloat paddingY = 5;
    CGFloat paddingX = 20;
    return UIEdgeInsetsMake(paddingY, paddingX, paddingY, paddingX);
    
}

//
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    // 2.設(shè)置每個格子的尺寸
//    layout.itemSize = CGSizeMake(250, 250);
    CGFloat nameW = [self withString:indexPath.section==0?self.stringArray1[indexPath.row]:self.stringArray2[indexPath.row]];

    
    return CGSizeMake((nameW<=80)?80:nameW, 30);
}

- (CGFloat)withString:(NSString *)string{

    
    
    //設(shè)置string字體  HelveticaNeue  Courier
    UIFont *font = [UIFont fontWithName:@"HelveticaNeue" size:15.0f];
   
    //根據(jù)字體得到nsstring的尺寸
    CGSize size = [string sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    //名字的高
//    CGFloat nameH = size.height;
    //名字的寬
    CGFloat nameW = size.width;
    
    return nameW>SCREEN_WIDTH?SCREEN_WIDTH-20:nameW;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSLog(@"點擊的是%ld組的第%ld個cell",indexPath.section,indexPath.row);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

效果圖

項目地址

WX20170306-181557.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末恭垦,一起剝皮案震驚了整個濱河市怪嫌,隨后出現(xiàn)的幾起案子有送,更是在濱河造成了極大的恐慌,老刑警劉巖盛险,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瞄摊,死亡現(xiàn)場離奇詭異,居然都是意外死亡苦掘,警方通過查閱死者的電腦和手機换帜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鹤啡,“玉大人惯驼,你說我怎么就攤上這事〉莨澹” “怎么了祟牲?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長抖部。 經(jīng)常有香客問我说贝,道長,這世上最難降的妖魔是什么慎颗? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任狂丝,我火速辦了婚禮,結(jié)果婚禮上哗总,老公的妹妹穿的比我還像新娘几颜。我一直安慰自己,他們只是感情好讯屈,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布蛋哭。 她就那樣靜靜地躺著,像睡著了一般涮母。 火紅的嫁衣襯著肌膚如雪谆趾。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天叛本,我揣著相機與錄音沪蓬,去河邊找鬼。 笑死来候,一個胖子當(dāng)著我的面吹牛跷叉,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼云挟,長吁一口氣:“原來是場噩夢啊……” “哼梆砸!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起园欣,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤帖世,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后沸枯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體日矫,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年绑榴,在試婚紗的時候發(fā)現(xiàn)自己被綠了搬男。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡彭沼,死狀恐怖缔逛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情姓惑,我是刑警寧澤褐奴,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站于毙,受9級特大地震影響敦冬,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜唯沮,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一脖旱、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧介蛉,春花似錦萌庆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至吹菱,卻和暖如春巍虫,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背鳍刷。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工占遥, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人输瓜。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓瓦胎,卻偏偏與公主長得像芬萍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子凛捏,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360

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