UICollectionView的基本應用和自定義布局

UICollectionView的自定義布局,在寫篇文章之前谭期,自己在方面遇到不少問題个盆,首先感謝幫助過我的人,自己也在網(wǎng)上找了不少資料舍沙,如有不足之處近上,請多多指教。

UICollectionView 基本使用
  • UICollectionView使用注意點
    • 1.創(chuàng)建UICollectionView必須要有布局參數(shù)(UICollectionViewFlowLayout比如流水性布局,UICollectionViewLayout空白布局拂铡,需要自己寫cell樣式)
    • 2.cell必須通過注冊
    • 3.cell必須自定義,系統(tǒng)cell沒有任何子控件
//注冊cell的ID
 static NSString * const ID = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
     // 創(chuàng)建布局參數(shù)
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    //設置 item的大小
    layout.itemSize = CGSizeMake(60, 60);
    //設置最小item的間距
    layout.minimumInteritemSpacing = 5;
    //設置最小行間距
    layout.minimumLineSpacing = 5;
    
    // 創(chuàng)建UICollectionView:黑色
    UICollectionView *collectionView = [[UICollectionView alloc]  initWithFrame:CGRectZero collectionViewLayout:layout];
    collectionView.backgroundColor = [UIColor brownColor];
    collectionView.center = self.view.center;
    collectionView.bounds = CGRectMake(0, 0, self.view.bounds.size.width, 200);
    [self.view addSubview:collectionView];
    
    // 設置數(shù)據(jù)源
    collectionView.dataSource = self;
    
    // 注冊cell
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([PhotoCell class])  bundle:nil] forCellWithReuseIdentifier:ID];
    
}


#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 10;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    PhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

    NSString *imageName = [NSString stringWithFormat:@"%ld",indexPath.item + 1];
    
    cell.image = [UIImage imageNamed:imageName];
    
    return cell;
}

xib創(chuàng)建cell


#import <UIKit/UIKit.h>

@interface PhotoCell : UICollectionViewCell

@property (nonatomic, strong) UIImage *image;

@end


//.m文件

#import "PhotoCell.h"

@interface PhotoCell ()
@property (weak, nonatomic) IBOutlet UIImageView *photoView;
@end

@implementation PhotoCell
- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)setImage:(UIImage *)image
{
    _image = image;
    
    _photoView.image = image;
    
}

@end

UICollectionView基本使用.png
自定義布局
//自定義布局需要知道的幾個方法

//作用:計算cell的布局
//調(diào)用:第一次布局collectionView或者collectionView刷新的時候調(diào)用
//初始化布局
- (void)prepareLayout;
 

/*
 UICollectionViewLayoutAttributes:確定cell的尺寸
 一個UICollectionViewLayoutAttributes對象就對應一個cell
 拿到UICollectionViewLayoutAttributes相當于拿到cell
 */
// 返回數(shù)組中的 UICollectionViewLayoutAttributes 布局屬性
/// 這個方法返回一個數(shù)組壹无, 數(shù)組存放rect的范圍內(nèi)所有元素的布局屬性葱绒,返回的數(shù)組決定了rect范圍內(nèi)所有的元素排布(frame)
 - (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
 
/**
 * 當 collectionView的顯示范圍繁盛改變的時候,是否需要重新刷新布局
 */
 - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds;
 
/**
 *  這個方法的返回值斗锭,就決定了collectionView停止?jié)L動時的偏移量
 *  proposedContentOffset  最終的偏移量
 *  velocity 滾動速率  這個參數(shù)可以了解到滾動的方向
 */
 - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity; 

/// 每一個item對應cell的UICollectionViewLayoutAttributes屬性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath地淀;

//collectionView內(nèi)容大小
 - (CGSize)collectionViewContentSize;

效果圖.gif

自定義布局的例子-(效果如上圖)

*****************控制器****************

#import "ViewController.h"

#import "CCLineLayout.h"

#import "CCCell.h"

#import "CCCircleLayout.h"

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) NSMutableArray *imageArray;

/**<#class#>*/
@property (nonatomic, weak) UICollectionView *collerView;

@end

@implementation ViewController


static NSString *const ID = @"cell";


- (NSMutableArray *)imageArray {
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
        for (int i = 0; i< 20 ;i ++) {
            
            [_imageArray addObject:[NSString stringWithFormat:@"%zd",i + 1]];
        }
    }
    
    return _imageArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    CCLineLayout *layout = [[CCLineLayout alloc] init];
   
    layout.itemSize = CGSizeMake(100, 100);
    
    CGFloat w = self.view.frame.size.width;
    
    CGRect frame = CGRectMake(0, 150, w, 200);
    
    UICollectionView *collerView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:layout];
    collerView.delegate = self;
    collerView.dataSource = self;
    [self.view addSubview:collerView];
    
    self.collerView = collerView;
    
    //注冊cell
    [collerView registerNib:[UINib nibWithNibName:NSStringFromClass([CCCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
    
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    if ([self.collerView.collectionViewLayout  isKindOfClass:[CCLineLayout class]]) {
        [self.collerView setCollectionViewLayout:[[CCCircleLayout alloc] init] animated:YES];
    } else {
        CCLineLayout *layout = [[CCLineLayout alloc] init];
        layout.itemSize = CGSizeMake(100, 100);
        [self.collerView setCollectionViewLayout:layout animated:YES];
    }
}



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



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.imageNmae = self.imageArray[indexPath.item];
    
    return cell;

}


//MARK:UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.imageArray removeObjectAtIndex:indexPath.item];
    [self.collerView deleteItemsAtIndexPaths:@[indexPath]];
    
}

@end

********************cell的第一個布局樣式******************

計算圖:

距離中心線的計算圖.png
#import <UIKit/UIKit.h>

@interface CCLineLayout : UICollectionViewFlowLayout

@end


#import "CCLineLayout.h"

@implementation CCLineLayout



///布局的初始化操作
- (void)prepareLayout {
    
     self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    CGFloat det = (self.collectionView.frame.size.width - self.itemSize.width)*0.5;
    // 內(nèi)邊距
    self.sectionInset = UIEdgeInsetsMake(0, det, 0, det);
}


/**
 * 當 collectionView的顯示范圍發(fā)生改變的時候,是否需要重新刷新布局
 */

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    
    
    return YES;
}



/**
 *   UICollectionViewLayoutAttributes
 *  1.一個cell對應一個UICollectionViewLayoutAttributes對象
 *  2.UICollectionViewLayoutAttributes對象決定了cell的frame
 */

/// 這個方法返回一個數(shù)組岖是, 數(shù)組存放rect的范圍內(nèi)所有元素的布局屬性帮毁,返回的數(shù)組決定了rect范圍內(nèi)所有的元素排布(frame)

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    
  //獲取布局屬性數(shù)組
    NSArray *array = [super layoutAttributesForElementsInRect:self.collectionView.bounds];
    //更改布局屬性
    for (UICollectionViewLayoutAttributes *attr in array) {
        //獲取到cell的中心點
        CGFloat cellCenterX = attr.center.x;
        // del是cell中心點 距離 collectionView中心點的距離
        CGFloat del = fabs((cellCenterX - self.collectionView.contentOffset.x) - self.collectionView.bounds.size.width *0.5);
        //根據(jù)間距 算出比例值
        CGFloat scale = 1- del/(self.collectionView.bounds.size.width *0.5) *0.25;
        //縮放
        attr.transform = CGAffineTransformMakeScale(scale, scale);

    }
    
    return array;
    
   
}

/**
 *  這個方法的返回值,就決定了collectionView停止?jié)L動時的偏移量
 *  proposedContentOffset  最終的偏移量
 *  velocity 滾動速率  這個參數(shù)可以了解到滾動的方向
 */
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity{
    
    CGFloat collectionViewW = self.collectionView.bounds.size.width;
    //最終偏移量
    CGPoint targetP = [super targetContentOffsetForProposedContentOffset:proposedContentOffset withScrollingVelocity:velocity];
    //獲取最終顯示的區(qū)域
    CGRect targetRect = CGRectMake(targetP.x, 0, collectionViewW, MAXFLOAT);

    //獲取布局屬性數(shù)組
    NSArray *arry =  [super layoutAttributesForElementsInRect:targetRect];
    
    //最小的間距
    CGFloat min = MAXFLOAT;
    
    for (UICollectionViewLayoutAttributes *arrt in arry) {
        //獲取距離中心點距離
        CGFloat del = (arrt.center.x - targetP.x) - self.collectionView.bounds.size.width *0.5;
        //找最小距離
        if (fabs(min) > fabs(del)) {
            min = del;
            
        }
        
    }
    
    targetP.x += min;
 
    if (targetP.x <  0) {
        targetP.x = 0;
    }
    return targetP;
}

@end

*******************cell的第二個布局樣式***************

#import <UIKit/UIKit.h>

@interface CCCircleLayout : UICollectionViewLayout

@end

#import "CCCircleLayout.h"

@interface CCCircleLayout()

@property (nonatomic, strong) NSMutableArray *attArray;

@end

@implementation CCCircleLayout


- (NSMutableArray *)attArray {
    
    if (!_attArray) {
        _attArray = [NSMutableArray array];
    }
    
    return _attArray;
}


//初始化布局
- (void)prepareLayout {
    
    [super prepareLayout];
    [self.attArray removeAllObjects];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    for (int i = 0; i < count; i ++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes *atts = [self layoutAttributesForItemAtIndexPath:indexPath];
        
        [self.attArray addObject:atts];
    }
    
}


/// 返回數(shù)組中的 UICollectionViewLayoutAttributes 布局屬性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    
    return self.attArray;
}


/// 每一個item對應cell的UICollectionViewLayoutAttributes屬性
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    //設置圓心半徑
    CGFloat radius = 70;
    
    //圓心的位置
    CGFloat oX = self.collectionView.frame.size.width *0.5;
    CGFloat oY = self.collectionView.frame.size.height *0.5;
    
    //創(chuàng)建 UICollectionViewLayoutAttributes屬性
    UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    //設置寬高
    attri.size = CGSizeMake(50, 50);
    
    CGFloat angle = ( 2 * M_PI /count) *indexPath.item;
    CGFloat centerX = oX + radius *sin(angle);
    CGFloat centerY = oY + radius*cos(angle);
    attri.center = CGPointMake(centerX, centerY);
    
 
    return attri;
    
    
}

@end





最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末豺撑,一起剝皮案震驚了整個濱河市烈疚,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌前硫,老刑警劉巖胞得,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異屹电,居然都是意外死亡阶剑,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進店門危号,熙熙樓的掌柜王于貴愁眉苦臉地迎上來牧愁,“玉大人,你說我怎么就攤上這事外莲≈戆耄” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵偷线,是天一觀的道長磨确。 經(jīng)常有香客問我,道長声邦,這世上最難降的妖魔是什么乏奥? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮亥曹,結(jié)果婚禮上邓了,老公的妹妹穿的比我還像新娘。我一直安慰自己媳瞪,他們只是感情好骗炉,可當我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蛇受,像睡著了一般句葵。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天笼呆,我揣著相機與錄音熊响,去河邊找鬼。 笑死诗赌,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的秸弛。 我是一名探鬼主播铭若,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼递览!你這毒婦竟也來了叼屠?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤绞铃,失蹤者是張志新(化名)和其女友劉穎镜雨,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體儿捧,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡荚坞,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了菲盾。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片颓影。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖懒鉴,靈堂內(nèi)的尸體忽然破棺而出诡挂,到底是詐尸還是另有隱情,我是刑警寧澤临谱,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布璃俗,位于F島的核電站,受9級特大地震影響悉默,放射性物質(zhì)發(fā)生泄漏城豁。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一麦牺、第九天 我趴在偏房一處隱蔽的房頂上張望钮蛛。 院中可真熱鬧,春花似錦剖膳、人聲如沸魏颓。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽甸饱。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間叹话,已是汗流浹背偷遗。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留驼壶,地道東北人氏豌。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像热凹,于是被迫代替她去往敵國和親泵喘。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,724評論 2 354

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