根據(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