iOS流佈局UICollectionView系列一——初識與簡單使用UICollectionView

iOS流佈局UICollectionView系列一——初識與簡單使用UICollectionView

1、簡介

        UICollectionView是iOS6以後引入的一個新的UI控件,它和UITableView有着諸多的類似之處,其中許多代理方法都十分相似。簡單來講,UICollectionView是比UITbleView更增強大的一個UI控件,有以下幾個方面:數組

一、支持水平和垂直兩種方向的佈局dom

二、經過layout配置方式進行佈局ide

三、相似於TableView中的cell特性外,CollectionView中的Item大小和位置能夠自由定義佈局

四、經過layout佈局回調的代理方法,能夠動態的定製每一個item的大小和collection的大致佈局屬性動畫

五、更增強大一點,徹底自定義一套layout佈局方案,能夠實現意想不到的效果atom

這篇博客,咱們主要討論CollectionView使用原生layout的方法和相關屬性,其餘特色和更強的制定化,會在後面的博客中介紹spa

 

2、先來實現一個最簡單的九宮格類佈局

        在瞭解UICollectionView的更多屬性前,咱們先來使用其進行一個最簡單的流佈局試試看,在controller的viewDidLoad中添加以下代碼:代理

    //建立一個layout佈局類
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    //設置佈局方向爲垂直流佈局
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //設置每一個item的大小爲100*100
    layout.itemSize = CGSizeMake(100, 100);
    //建立collectionView 經過一個佈局策略layout來建立
    UICollectionView * collect = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    //代理設置
    collect.delegate=self;
    collect.dataSource=self;
    //註冊item類型 這裏使用系統的類型
    [collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];
   
    [self.view addSubview:collect];

這裏有一點須要注意,collectionView在完成代理回調前,必須註冊一個cell,相似以下:code

[collect registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellid"];

這和tableView有些相似,又有些不一樣,由於tableView除了註冊cell的方法外,還能夠經過臨時建立來作:對象

//tableView在從複用池中取cell的時候,有以下兩種方法
//使用這種方式若是複用池中無,是能夠返回nil的,咱們在臨時建立便可
- (nullable __kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier;
//6.0後使用以下的方法直接從註冊的cell類獲取建立,若是沒有註冊 會崩潰
- (__kindof UITableViewCell *)dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(6_0);

咱們能夠分析:由於UICollectionView是iOS6.0以前的新類,所以這裏統一了從複用池中獲取cell的方法,沒有再提供能夠返回nil的方式,而且在UICollectionView的回調代理中,只能使用從複用池中獲取cell的方式進行cell的返回,其餘方式會崩潰,例如:

//這是正確的方法
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
    return cell;
}

//這樣作會崩潰
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
    UICollectionViewCell * cell = [[UICollectionViewCell alloc]init];
    return cell;
}

上面錯誤的方式會崩潰,信息以下,讓咱們使用從複用池中取cell的方式:

上面的設置完成後,咱們來實現以下幾個代理方法:

這裏與TableView的回調方式十分相似

//返回分區個數
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
//返回每一個分區的item個數
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 10;
}
//返回每一個item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell * cell  = [collectionView dequeueReusableCellWithReuseIdentifier:@"cellid" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:arc4random()%255/255.0 green:arc4random()%255/255.0 blue:arc4random()%255/255.0 alpha:1];
    return cell;
}

效果以下:

一樣,若是內容的大小超出一屏,和tableView相似是能夠進行視圖滑動的。

還有一點細節,咱們在上面設置佈局方式的時候設置了垂直佈局:

layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//這個是水平佈局
//layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;

這樣系統會在一行充滿後進行第二行的排列,若是設置爲水平佈局,則會在一列充滿後,進行第二列的佈局,這種方式也被稱爲流式佈局

3、UICollectionView中的經常使用方法和屬性

//經過一個佈局策略初識化CollectionView
- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout;

//獲取和設置collection的layout
@property (nonatomic, strong) UICollectionViewLayout *collectionViewLayout;

//數據源和代理
@property (nonatomic, weak, nullable) id <UICollectionViewDelegate> delegate;
@property (nonatomic, weak, nullable) id <UICollectionViewDataSource> dataSource;

//從一個class或者xib文件進行cell(item)的註冊
- (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(nullable UINib *)nib forCellWithReuseIdentifier:(NSString *)identifier;

//下面兩個方法與上面類似,這裏註冊的是頭視圖或者尾視圖的類
//其中第二個參數是設置 頭視圖或者尾視圖 系統爲咱們定義好了這兩個字符串
//UIKIT_EXTERN NSString *const UICollectionElementKindSectionHeader NS_AVAILABLE_IOS(6_0);
//UIKIT_EXTERN NSString *const UICollectionElementKindSectionFooter NS_AVAILABLE_IOS(6_0);
- (void)registerClass:(nullable Class)viewClass forSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier;
- (void)registerNib:(nullable UINib *)nib forSupplementaryViewOfKind:(NSString *)kind withReuseIdentifier:(NSString *)identifier;

//這兩個方法是從複用池中取出cell或者頭尾視圖
- (__kindof UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
- (__kindof UICollectionReusableView *)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;

//設置是否容許選中 默認yes
@property (nonatomic) BOOL allowsSelection;

//設置是否容許多選 默認no
@property (nonatomic) BOOL allowsMultipleSelection;

//獲取全部選中的item的位置信息
- (nullable NSArray<NSIndexPath *> *)indexPathsForSelectedItems; 

//設置選中某一item,並使視圖滑動到相應位置,scrollPosition是滑動位置的相關參數,以下:
/*
typedef NS_OPTIONS(NSUInteger, UICollectionViewScrollPosition) {
    //無
    UICollectionViewScrollPositionNone                 = 0,
    //垂直佈局時使用的 對應上中下
    UICollectionViewScrollPositionTop                  = 1 << 0,
    UICollectionViewScrollPositionCenteredVertically   = 1 << 1,
    UICollectionViewScrollPositionBottom               = 1 << 2,
    //水平佈局時使用的  對應左中右
    UICollectionViewScrollPositionLeft                 = 1 << 3,
    UICollectionViewScrollPositionCenteredHorizontally = 1 << 4,
    UICollectionViewScrollPositionRight                = 1 << 5
};
*/
- (void)selectItemAtIndexPath:(nullable NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UICollectionViewScrollPosition)scrollPosition;

//將某一item取消選中
- (void)deselectItemAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated;

//從新加載數據
- (void)reloadData;

//下面這兩個方法,能夠從新設置collection的佈局,後面的方法多了一個佈局完成後的回調,iOS7後能夠用
//使用這兩個方法能夠產生很是炫酷的動畫效果
- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated;
- (void)setCollectionViewLayout:(UICollectionViewLayout *)layout animated:(BOOL)animated completion:(void (^ __nullable)(BOOL finished))completion NS_AVAILABLE_IOS(7_0);

//下面這些方法更增強大,咱們能夠對佈局更改後的動畫進行設置
//這個方法傳入一個佈局策略layout,系統會開始進行佈局渲染,返回一個UICollectionViewTransitionLayout對象
//這個UICollectionViewTransitionLayout對象管理動畫的相關屬性,咱們能夠進行設置
- (UICollectionViewTransitionLayout *)startInteractiveTransitionToCollectionViewLayout:(UICollectionViewLayout *)layout completion:(nullable UICollectionViewLayoutInteractiveTransitionCompletion)completion NS_AVAILABLE_IOS(7_0);
//準備好動畫設置後,咱們須要調用下面的方法進行佈局動畫的展現,以後會調用上面方法的block回調
- (void)finishInteractiveTransition NS_AVAILABLE_IOS(7_0);
//調用這個方法取消上面的佈局動畫設置,以後也會進行上面方法的block回調
- (void)cancelInteractiveTransition NS_AVAILABLE_IOS(7_0);

//獲取分區數
- (NSInteger)numberOfSections;

//獲取某一分區的item數
- (NSInteger)numberOfItemsInSection:(NSInteger)section;

//下面兩個方法獲取item或者頭尾視圖的layout屬性,這個UICollectionViewLayoutAttributes對象
//存放着佈局的相關數據,能夠用來作徹底自定義佈局,後面博客會介紹
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;
- (nullable UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath;

//獲取某一點所在的indexpath位置
- (nullable NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point;

//獲取某個cell所在的indexPath
- (nullable NSIndexPath *)indexPathForCell:(UICollectionViewCell *)cell;

//根據indexPath獲取cell
- (nullable UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath;

//獲取全部可見cell的數組
- (NSArray<__kindof UICollectionViewCell *> *)visibleCells;

//獲取全部可見cell的位置數組
- (NSArray<NSIndexPath *> *)indexPathsForVisibleItems;

//下面三個方法是iOS9中新添加的方法,用於獲取頭尾視圖
- (UICollectionReusableView *)supplementaryViewForElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0);
- (NSArray<UICollectionReusableView *> *)visibleSupplementaryViewsOfKind:(NSString *)elementKind NS_AVAILABLE_IOS(9_0);
- (NSArray<NSIndexPath *> *)indexPathsForVisibleSupplementaryElementsOfKind:(NSString *)elementKind NS_AVAILABLE_IOS(9_0);

//使視圖滑動到某一位置,能夠帶動畫效果
- (void)scrollToItemAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UICollectionViewScrollPosition)scrollPosition animated:(BOOL)animated;

//下面這些方法用於動態添加,刪除,移動某些分區獲取items
- (void)insertSections:(NSIndexSet *)sections;
- (void)deleteSections:(NSIndexSet *)sections;
- (void)reloadSections:(NSIndexSet *)sections;
- (void)moveSection:(NSInteger)section toSection:(NSInteger)newSection;

- (void)insertItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)deleteItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)reloadItemsAtIndexPaths:(NSArray<NSIndexPath *> *)indexPaths;
- (void)moveItemAtIndexPath:(NSIndexPath *)indexPath toIndexPath:(NSIndexPath *)newIndexPath;

 

專一技術,熱愛生活,交流技術,也作朋友。

——琿少 QQ羣:203317592

相關文章
相關標籤/搜索