ios - collectionView的使用

-. 布局

UICollectionViewFlowLayout流水布局
  1. 通过UICollectionViewFlowLayout对象进行布局( 如果布局的尺寸是固定的,例如:item的尺寸大小都是固定,可以使用全局属性,即设置下文中layout )
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 1.设置列间距
    layout.minimumInteritemSpacing = 1;
    // 2.设置行间距
    layout.minimumLineSpacing = 1;
    // 3.设置每个item的大小
    layout.itemSize = CGSizeMake(50, 50);
    // 4.设置Item的估计大小,用于动态设置item的大小,结合自动布局(self-sizing-cell)
    layout.estimatedItemSize = CGSizeMake(320, 60);
    // 5.设置布局方向
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    // 6.设置头视图尺寸大小
    layout.headerReferenceSize = CGSizeMake(50, 50);
    // 7.设置尾视图尺寸大小
    layout.footerReferenceSize = CGSizeMake(50, 50);
    // 8.设置分区(组)的EdgeInset(四边距)
    layout.sectionInset = UIEdgeInsetsMake(10, 20, 30, 40);
    // 9.10.设置分区的头视图和尾视图是否始终固定在屏幕上边和下边
    layout.sectionFootersPinToVisibleBounds = YES;
    layout.sectionHeadersPinToVisibleBounds = YES;
  1. 通过遵守UICollectionViewDelegateFlowLayout实现代理方法来布局(非固定情况则需要通过数据源方法)
- (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;
二. 数据源方法
//设置分区数(必须实现)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

//设置每个分区的item个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{ 
    return 5;  
}

//设置返回每个item的属性必须实现)
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [self.collection dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    return cell;
}

//对头视图或者尾视图进行设置
- (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时触发的方法
- (void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath*)destinationIndexPath NS_AVAILABLE_IOS(9_0); {

}
三. 常用到的代理方法
//是否允许某个Item的高亮,返回NO,则不能进入高亮状态
- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//当item高亮时触发的方法
- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//结束高亮状态时触发的方法
- (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;
}

//已经选中某个item时触发的方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//取消选中某个Item时触发的方法
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//将要加载某个Item时调用的方法
- (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0); {

}

//将要加载头尾视图时调用的方法
- (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(8_0); {

}

//已经展示某个Item时触发的方法
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath; {

}

//已经展示某个头尾视图时触发的方法
- (void)collectionView:(UICollectionView *)collectionView didEndDisplayingSupplementaryView:(UICollectionReusableView *)view forElementOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath; {

}

//这个方法设置是否展示长按菜单
- (BOOL)collectionView:(UICollectionView *)collectionView shouldShowMenuForItemAtIndexPath:(NSIndexPath *)indexPath; {
    return YES;
}

//这个方法用于设置要展示的菜单选项
- (BOOL)collectionView:(UICollectionView *)collectionView canPerformAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender; {
    return YES;
}

//这个方法用于实现点击菜单按钮后的触发方法,通过测试,只有copy,cut和paste三个方法可以使用
- (void)collectionView:(UICollectionView *)collectionView performAction:(SEL)action forItemAtIndexPath:(NSIndexPath *)indexPath withSender:(nullable id)sender; {
    //通过下面的方式可以将点击按钮的方法名打印出来:
    NSLog(@"%@",NSStringFromSelector(action));
}

//collectionView进行重新布局时调用的方法
//- (nonnull UICollectionViewTransitionLayout *)collectionView:(UICollectionView *)collectionView transitionLayoutForOldLayout:(UICollectionViewLayout *)fromLayout newLayout:(UICollectionViewLayout *)toLayout; {
//
//}
四. collectionView的属性和相关方法
//通过一个布局策略初识化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;
五,自定义布局
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,302评论 5 470
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,232评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,337评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,977评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,920评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,194评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,638评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,319评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,455评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,379评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,426评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,106评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,696评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,786评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,996评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,467评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,043评论 2 341

推荐阅读更多精彩内容