ios - collectionView的使用

-. 布局

UICollectionViewFlowLayout流水布局
  1. 通過UICollectionViewFlowLayout對象進行布局( 如果布局的尺寸是固定的,例如:item的尺寸大小都是固定,可以使用全局屬性,即設(shè)置下文中l(wèi)ayout )
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 1.設(shè)置列間距
    layout.minimumInteritemSpacing = 1;
    // 2.設(shè)置行間距
    layout.minimumLineSpacing = 1;
    // 3.設(shè)置每個item的大小
    layout.itemSize = CGSizeMake(50, 50);
    // 4.設(shè)置Item的估計大小,用于動態(tài)設(shè)置item的大小,結(jié)合自動布局(self-sizing-cell)
    layout.estimatedItemSize = CGSizeMake(320, 60);
    // 5.設(shè)置布局方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 6.設(shè)置頭視圖尺寸大小
    layout.headerReferenceSize = CGSizeMake(50, 50);
    // 7.設(shè)置尾視圖尺寸大小
    layout.footerReferenceSize = CGSizeMake(50, 50);
    // 8.設(shè)置分區(qū)(組)的EdgeInset(四邊距)
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 30, 40);
    // 9.10.設(shè)置分區(qū)的頭視圖和尾視圖是否始終固定在屏幕上邊和下邊
    layout.sectionFootersPinToVisibleBounds = YES;
    layout.sectionHeadersPinToVisibleBounds = YES;
  1. 通過遵守UICollectionViewDelegateFlowLayout實現(xiàn)代理方法來布局(非固定情況則需要通過數(shù)據(jù)源方法)
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
二. 數(shù)據(jù)源方法
//設(shè)置分區(qū)數(shù)(必須實現(xiàn))
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//設(shè)置每個分區(qū)的item個數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 
    return 5;  
}

//設(shè)置返回每個item的屬性必須實現(xiàn))
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    return cell;
}

//對頭視圖或者尾視圖進行設(shè)置
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier;
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        identifier = @"headerView";
    } else {
        identifier = @"footerView";
    }
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:identifier forIndexPath:indexPath];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 120, 30)];
    [view addSubview:label];
    
    if (indexPath.section == 0) {
        label.text = @"section1";
    }else {
        label.text = @"section2";
    }
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        view.backgroundColor = [UIColor redColor];
    } else {
        view.backgroundColor = [UIColor purpleColor];

    }
    return view;
}

//是否允許移動Item
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(9_0){
    return YES;
}

//移動Item時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0); {

}
三. 常用到的代理方法
//是否允許某個Item的高亮,返回NO,則不能進入高亮狀態(tài)
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//當(dāng)item高亮?xí)r觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//結(jié)束高亮狀態(tài)時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//是否可以選中某個Item,返回NO,則不能選中
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//是否可以取消選中某個Item
- (BOOL)collectionView:(UICollectionView *)collectionView shouldDeselectItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//已經(jīng)選中某個item時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//取消選中某個Item時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//將要加載某個Item時調(diào)用的方法
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0); {

}

//將要加載頭尾視圖時調(diào)用的方法
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0); {

}

//已經(jīng)展示某個Item時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//已經(jīng)展示某個頭尾視圖時觸發(fā)的方法
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath; {

}

//這個方法設(shè)置是否展示長按菜單
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//這個方法用于設(shè)置要展示的菜單選項
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender; {
    return YES;
}

//這個方法用于實現(xiàn)點擊菜單按鈕后的觸發(fā)方法,通過測試,只有copy,cut和paste三個方法可以使用
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender; {
    //通過下面的方式可以將點擊按鈕的方法名打印出來:
    NSLog(@"%@",NSStringFromSelector(action));
}

//collectionView進行重新布局時調(diào)用的方法
//- (nonnull UICollectionViewTransitionLayout *)collectionView:(UICollectionView *)collectionView transitionLayoutForOldLayout:(UICollectionViewLayout *)fromLayout newLayout:(UICollectionViewLayout *)toLayout; {
//
//}
四. collectionView的屬性和相關(guān)方法
//通過一個布局策略初識化CollectionView
    - (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout;
    
    //獲取和設(shè)置collection的layout
    @property (nonatomic, strong) UICollectionViewLayout *collectionViewLayout;
    
    //數(shù)據(jù)源和代理
    @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;
    
    //下面兩個方法與上面相似,這里注冊的是頭視圖或者尾視圖的類
    //其中第二個參數(shù)是設(shè)置 頭視圖或者尾視圖 系統(tǒng)為我們定義好了這兩個字符串
    //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;
    
    //這兩個方法是從復(fù)用池中取出cell或者頭尾視圖
    - (__kindof UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
    - (__kindof UICollectionReusableView *)dequeueReusableSupplementaryViewOfKind:(NSString *)elementKind withReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath;
    
    //設(shè)置是否允許選中 默認(rèn)yes
    @property (nonatomic) BOOL allowsSelection;
    
    //設(shè)置是否允許多選 默認(rèn)no
    @property (nonatomic) BOOL allowsMultipleSelection;
    
    //獲取所有選中的item的位置信息
    - (nullable NSArray<NSIndexPath *> *)indexPathsForSelectedItems;
    
    //設(shè)置選中某一item,并使視圖滑動到相應(yīng)位置,scrollPosition是滑動位置的相關(guān)參數(shù),如下:
    /*
     typedef NS_OPTIONS(NSUInteger, UICollectionViewScrollPosition) {
     //無
     UICollectionViewScrollPositionNone                 = 0,
     //垂直布局時使用的 對應(yīng)上中下
     UICollectionViewScrollPositionTop                  = 1 << 0,
     UICollectionViewScrollPositionCenteredVertically   = 1 << 1,
     UICollectionViewScrollPositionBottom               = 1 << 2,
     //水平布局時使用的  對應(yīng)左中右
     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;
    
    //重新加載數(shù)據(jù)
    - (void)reloadData;
    
    //下面這兩個方法,可以重新設(shè)置collection的布局,后面的方法多了一個布局完成后的回調(diào),iOS7后可以用
    //使用這兩個方法可以產(chǎn)生非常炫酷的動畫效果
    - (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);
    
    //下面這些方法更加強大,我們可以對布局更改后的動畫進行設(shè)置
    //這個方法傳入一個布局策略layout,系統(tǒng)會開始進行布局渲染,返回一個UICollectionViewTransitionLayout對象
    //這個UICollectionViewTransitionLayout對象管理動畫的相關(guān)屬性,我們可以進行設(shè)置
    - (UICollectionViewTransitionLayout *)startInteractiveTransitionToCollectionViewLayout:(UICollectionViewLayout *)layout completion:(nullable UICollectionViewLayoutInteractiveTransitionCompletion)completion NS_AVAILABLE_IOS(7_0);
    //準(zhǔn)備好動畫設(shè)置后,我們需要調(diào)用下面的方法進行布局動畫的展示,之后會調(diào)用上面方法的block回調(diào)
    - (void)finishInteractiveTransition NS_AVAILABLE_IOS(7_0);
    //調(diào)用這個方法取消上面的布局動畫設(shè)置,之后也會進行上面方法的block回調(diào)
    - (void)cancelInteractiveTransition NS_AVAILABLE_IOS(7_0);
    
    //獲取分區(qū)數(shù)
    - (NSInteger)numberOfSections;
    
    //獲取某一分區(qū)的item數(shù)
    - (NSInteger)numberOfItemsInSection:(NSInteger)section;
    
    //下面兩個方法獲取item或者頭尾視圖的layout屬性,這個UICollectionViewLayoutAttributes對象
    //存放著布局的相關(guān)數(shù)據(jù),可以用來做完全自定義布局,后面博客會介紹
    - (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;
    
    //根據(jù)indexPath獲取cell
    - (nullable UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath;
    
    //獲取所有可見cell的數(shù)組
    - (NSArray<__kindof UICollectionViewCell *> *)visibleCells;
    
    //獲取所有可見cell的位置數(shù)組
    - (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;
    
    //下面這些方法用于動態(tài)添加,刪除,移動某些分區(qū)獲取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;
五,自定義布局
UICollectionViewDelegateFlowLayout可以繼承這個自定義

自定義UICollectionViewLayout(抽象類):

- (void)prepareLayout
{
    [super prepareLayout];
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableDictionary *dict;
    dict[@"0"] = @1;
    dict[@"1"] = @2;
    UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attrs.transform3D = CATransform3DMakeRotation(arc4random_uniform(M_1_PI), 1, 1, 1);
    // zIndex越大,就越在上面
    attrs.zIndex =  [self.collectionView numberOfItemsInSection:indexPath.section]-indexPath.item;
    @property (nonatomic) CGRect frame;
    @property (nonatomic) CGPoint center;
    @property (nonatomic) CGSize size;
    @property (nonatomic) CATransform3D transform3D;
    @property (nonatomic) CGRect bounds NS_AVAILABLE_IOS(7_0);
    @property (nonatomic) CGAffineTransform transform NS_AVAILABLE_IOS(7_0);
    @property (nonatomic) CGFloat alpha;
    @property (nonatomic) NSInteger zIndex; // default is 0
    @property (nonatomic, getter=isHidden) BOOL hidden; // As an optimization, UICollectionView might not create a view for items whose hidden attribute is YES
    @property (nonatomic, strong) NSIndexPath *indexPath;    return attrs;
    //    ABS(1-2);絕對值     CGRectIntersectsRect(<#CGRect rect1#>, <#CGRect rect2#>) 這要和rect1相交就都算;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *array = [NSMutableArray array];
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    for (int i=0; i<count; i++) {
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
        [array addObject:attrs];
    }
    return array;
}

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}
從寫方法計算contentsize

注:參考自http://my.oschina.net/u/2340880/blog/522682

最后編輯于
?著作權(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)容

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