IOS-UICollectionView及其常用方法

UICollectionViewLayout

UICollectionViewLayout是UICollectionView比UITableView強(qiáng)大的原因,通過 UICollectionViewLayoutAttributes 類來管理 cell 、 Supplementary View 和 Decoration View 的 位置 、 transform 、 alpha 、 hidden 等等。

UICollectionViewLayout這個類只是一個基類,我們給UICollectionView使用的都是它的 子類 。系統(tǒng)為我們提供了一個最常用的layout為 UICollectionViewFlowLayout 。當(dāng)UICollectionViewLayout滿足不了我們的需求時,我們可以 子類化UICollectionViewLayout 或者 自定義layout 。

我們先來了解它內(nèi)部的常用的屬性:

//同一組當(dāng)中,行與行之間的最小行間距,但是不同組之間的不同行cell不受這個值影響。
@property (nonatomic) CGFloat minimumLineSpacing;
//同一行的cell中互相之間的最小間隔,設(shè)置這個值之后,那么cell與cell之間至少為這個值
@property (nonatomic) CGFloat minimumInteritemSpacing;
//每個cell統(tǒng)一尺寸
@property (nonatomic) CGSize itemSize;
//滑動反向,默認(rèn)滑動方向是垂直方向滑動
@property (nonatomic) UICollectionViewScrollDirection scrollDirection;
//每一組頭視圖的尺寸。如果是垂直方向滑動,則只有高起作用;如果是水平方向滑動,則只有寬起作用。
@property (nonatomic) CGSize headerReferenceSize;
//每一組尾部視圖的尺寸。如果是垂直方向滑動,則只有高起作用;如果是水平方向滑動,則只有寬起作用。
@property (nonatomic) CGSize footerReferenceSize;
//每一組的內(nèi)容縮進(jìn)
@property (nonatomic) UIEdgeInsets sectionInset;

UICollectionView類似于UITableView和UITableViewController,使用UICollectionView必須實現(xiàn)
UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout這三個協(xié)議。
代碼如下:

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

@end

@implementation ViewController

NSString *identifier = @"cell";
/**
 *  注冊增補(bǔ)視圖用的
 */
NSString *headerIdentifier = @"header";
NSString *footerIdentifier = @"footer";

- (void)viewDidLoad {
    [super viewDidLoad];
    // 創(chuàng)建布局對象
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 設(shè)置最小行間距
    flowLayout.minimumLineSpacing = 50;
    // 最小列間距
    flowLayout.minimumInteritemSpacing = 40;
    /**
     *   設(shè)置item的大小 格局item的大小自動布局列間距
     *
     *  @param 50 寬
     *  @param 50 高
     *
     *  @return
     */
    flowLayout.itemSize = CGSizeMake(150, 120);
    /**
     *  設(shè)置自動滾動的方向 垂直或者橫向
     */
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    /**
     *  設(shè)置集合視圖內(nèi)邊距的大小
     *
     *  @param 20 上
     *  @param 20 左
     *  @param 20 下
     *  @param 20 右
     *
     *  @return  UIEdgeInsetsMake  與下面的方法相同  -(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
     */
    flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    /**
     *  設(shè)置header區(qū)域大小
     *
     *  @param 414 414
     *  @param 70  無用
     *
     *  @return
     */
    flowLayout.headerReferenceSize = CGSizeMake(414, 70);
    /**
     *  設(shè)置footer區(qū)域的大小
     *
     *  @param 414 無用
     *  @param 70  自己設(shè)置
     *
     *  @return  如果寫了這里必須設(shè)置注冊
     */
//    flowLayout.footerReferenceSize = CGSizeMake(414, 70);
    
    /**
     創(chuàng)建UICollectionView前必須先創(chuàng)建布局對象UICollectionViewFlowLayout
     
     - returns: UICollectionViewFlowLayout(布局對象)
     */
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    //設(shè)置屬性
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    // 是否顯示垂直方向指示標(biāo), 繼承于UIScrollView, 他的方法可以調(diào)用
    collectionView.showsVerticalScrollIndicator = NO;

    // 注冊
    [collectionView registerClass:[TestCollectionViewCell class] forCellWithReuseIdentifier:identifier];
    
    /**
     *  注冊增補(bǔ)視圖
     */
    [collectionView registerClass:[HeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier];

   [collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:footerIdentifier];
    // 添加到視圖上
    [self.view addSubview:collectionView];

}

#warning UICollectionViewDataSource

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    TestCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    cell.contentView.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1.0];
    cell.imageView.image = [UIImage imageNamed:@"Icon@2x"];
    cell.label.text = @"測試";
    return cell;
}

// 設(shè)置每個分區(qū)返回多少item
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 15;
}

// 設(shè)置集合視圖有多少個分區(qū)
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
   }

/**
 *  返回增補(bǔ)視圖
 *
 *  @param collectionView
 *  @param kind
 *  @param indexPath
 *
 *  @return
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    // 如果是頭視圖
    if (kind == UICollectionElementKindSectionHeader) {
        // 從重用池里面取
        HeaderCollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerIdentifier forIndexPath:indexPath];
        headerView.backgroundColor =[UIColor orangeColor];
        headerView.titleLabel.text = @"測試";
        return headerView;
    }else{
        UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:footerIdentifier forIndexPath:indexPath];
//        footerView.backgroundColor = [UIColor brownColor];
//        return footerView;
        return nil;
    }
    
}

#warning UICollectionViewDelegate
// 點擊item觸發(fā)的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    /**
    推出的頁面的布局一般在這里寫 最小行間距.列間距等
     - returns:
     */
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    DetailCollectionViewController *detailVC = [[DetailCollectionViewController alloc] initWithCollectionViewLayout:flowLayout];
    
    [self.navigationController pushViewController:detailVC animated:YES ];
     NSLog(@"%ld-%ld",indexPath.section,indexPath.row);
    
}

/**
 *  指定那些路徑可以被點擊
 *
 *  @param collectionView
 *  @param indexPath
 *
 *  @return
// */
//-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    
//    if (indexPath.section == 0) {
//        return NO;
//    }
//    return YES;
//}


#warning UICollectionViewDelegateFlowLayout

/**
 *  返回內(nèi)邊距的上左下右的距離
 *
 *  @param collectionView       UICollectionView
 *  @param collectionViewLayout UICollectionViewLayout
 *  @param section
 *
 *  @return
 */
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    
    
    return UIEdgeInsetsMake(30, 30, 30, 30);
    
}

我們首先了解UICollectionView的工作流程,先將UICollectionView分成視圖、數(shù)據(jù)源和代理方法、UICollectionViewLayout三方面來進(jìn)行介紹

一、視圖

UICollectionView上面顯示內(nèi)容的視圖有三種Cell視圖、Supplementary View和Decoration View。
Cell視圖
CollectionView只要內(nèi)容由他展示數(shù)據(jù)從數(shù)據(jù)源獲取出來,類似于UITableView中的cell;
Supplementary View
他展示的是每一組的信息類似于cell,他也是從數(shù)據(jù)員獲取的數(shù)據(jù),但是與cell有一點不同,他并不是強(qiáng)烈需要的。如flow layout中的header 和 footer;
Decoration View
這個視圖是一個裝飾視圖,它沒有什么功能性,它不跟數(shù)據(jù)源有任何關(guān)系,它完全屬于layout對象。

二、數(shù)據(jù)源和代理方法

1、注冊cell

在使用數(shù)據(jù)源返回cell給collectionView之前,我們必須先要注冊,用來進(jìn)行重用。
registerClass: forCellWithReuseIdentifier:
registerNib: forCellWithReuseIdentifier:

顯而易見,前面兩個方法是注冊cell,其中,注冊的方式有兩種,第一種是直接注冊class,它重用的時候會調(diào)用[[UICollectionView alloc] init]這樣的初始化方法創(chuàng)建cell;另外一種是注冊nib,它會自動加載nib文件。
注冊的之后,我們?nèi)绾沃赜茫?br> 在數(shù)據(jù)源方法當(dāng)中返回 cell
的方法當(dāng)中通過dequeueReusableCellWithReuseIdentifier:forIndexPath:
方法獲取cell。

示例代碼:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellReuseIdentify forIndexPath:indexPath];
cell.backgroundColor = [UIColor lightGrayColor]; cell.textLabel.text = [NSString stringWithFormat:@"(%zd,%zd)", indexPath.section, indexPath.row]; return cell;
}

2、數(shù)據(jù)源方法

數(shù)據(jù)源方法與UITableView類似,主要有:
numberOfSectionsInCollectionView:
collectionView: numberOfItemsInSection:
collectionView: cellForItemAtIndexPath:
collectionView: viewForSupplementaryElementOfKind: atIndexPath:

3、代理方法

數(shù)據(jù)源為UICollectionView提供數(shù)據(jù)相關(guān)的內(nèi)容,而代理則主要負(fù)責(zé)用戶交互、與數(shù)據(jù)無關(guān)的視圖外形。主要分成兩部分:

1、通過調(diào)用代理方法,管理視圖的選中、高亮

collectionView:shouldDeselectItemAtIndexPath:
collectionView:didSelectItemAtIndexPath:
collectionView:didDeselectItemAtIndexPath:
collectionView:shouldHighlightItemAtIndexPath:
collectionView:didHighlightItemAtIndexPath:
collectionView:didUnhighlightItemAtIndexPath:

2、長按cell,顯示編輯菜單 當(dāng)用戶長按cell時,collection view視圖會顯示一個編輯菜單。這個編輯菜單可以用來剪切、復(fù)制和粘貼cell。不過,要顯示這個編輯菜單需要滿足很多條件,代理對象必須實現(xiàn)下面三個方法:

collectionView:shouldShowMenuForItemAtIndexPath:
collectionView:canPerformAction:forItemAtIndexPath:withSender:
collectionView:performAction:forItemAtIndexPath:withSender:

對于指定要編輯的cell,collectionView:shouldShowMenuForItemAtIndexPath:
方法需要返回YES

collectionView:canPerformAction:forItemAtIndexPath:withSender:
方法中,對于剪切、復(fù)制、粘貼三種action至少有一個返回YES。其實,編輯菜單是有很多種action的,但是對于UICollectionView來說,它僅僅支持的剪切、復(fù)制、粘貼三個,所以說這個代理方法至少支持這三種的一種。
剪切、復(fù)制、粘貼的方法名是:
cut:
copy:
paste:

當(dāng)上面的條件都滿足了,用戶就可以長按cell顯示出編輯菜單,然后選擇對應(yīng)的action,從而就會回調(diào)delegate的collectionView:performAction:forItemAtIndexPath:withSender: 方法去做對應(yīng)的事情。

當(dāng)我們想控制編輯菜單僅僅顯示復(fù)制和粘貼時,我們就可以在collectionView:canPerformAction:forItemAtIndexPath:withSender:
方法中進(jìn)行操作,具體請見下面代碼:

- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
    if ([NSStringFromSelector(action) isEqualToString:@"copy:"]
        || [NSStringFromSelector(action) isEqualToString:@"paste:"])
        return YES;
    return NO;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 翻譯自“Collection View Programming Guide for iOS” 0 關(guān)于iOS集合視...
    lakerszhy閱讀 4,071評論 1 22
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,245評論 4 61
  • 每天忙著追求, 失去停下來的德性, 于是成了見利忘義、 出賣自己的賤人! 我們所盯住的, 無非利; 我們所忘掉的,...
    再湊熱鬧閱讀 274評論 1 0
  • 第18章 如何閱讀哲學(xué) 閱讀哲學(xué)的提示 在閱讀任何哲學(xué)作品是最重要的就是要發(fā)現(xiàn)問題,或是找到書中想要回答的問題。...
    RainbowKang閱讀 258評論 0 0
  • 單行注釋:在方法的地方按 Command+/ 標(biāo)注的功能,快捷鍵是Command + Option + / 需要在...
    iOS_Developer閱讀 318評論 0 0

友情鏈接更多精彩內(nèi)容