collectionView技巧

  • 组头、组尾
  • item的重排问题
  • sectionInset内边距
  • 自定义Layout
  • 第三方CHTCollectionViewWaterfallLayout的使用

组头、组尾

//每段的段头视图,或者段尾视图
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        HJCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        SWPWikiModel *wikiModel = self.dataSourceArray[indexPath.section];
        view.backgroundColor = [UIColor whiteColor];
        if ([wikiModel.kind isEqualToString:@"group"]) {
            view.kindLabel.text =  @"食物类别";
        }else if ([wikiModel.kind isEqualToString:@"brand"]) {
            view.kindLabel.text =  @"热门品牌";
        }else if ([wikiModel.kind isEqualToString:@"restaurant"]) {
            view.kindLabel.text =  @"连锁餐饮";
        }else{
            view.kindLabel.text =  @"其他类别";
        }
        
        return view;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        HJCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        view.backgroundColor = [UIColor colorWithRed:218/256.0 green:218/256.0 blue:218/256.0 alpha:1];
        view.kindLabel.backgroundColor = [UIColor colorWithRed:218/256.0 green:218/256.0 blue:218/256.0 alpha:1];
        return view;
    }
    return nil;
}

item的重排问题

  1. 添加长按手势UILongpressGestureRecognizer
-(void)addLongPressGestureToCollectionView{
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self      action:@selector(longPressHandle:)];
        [self.collectionView addGestureRecognizer:longPressGesture];
}
  1. 监听手势状态state变化
1.beginInteractiveMovementForItemAtIndexPath: //开始移动
2.updateInteractiveMovementTargetPosition:       //更新坐标
3.endInteractiveMovement:                                    //结束移动
4.cancelInteractiveMovement:                                //取消移动
  1. dataSourceArray删除、添加数据
第三步:dataSourceArray删除,插入数据
#pragma mark - Action
 /*cell的移动(从oldindex 移到 newindex)*/
 -(void)collectionView:(UICollectionView *)collectionView moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath: (NSIndexPath *)destinationIndexPath{
//0.获取移动的起点和终点
       NSInteger from = sourceIndexPath.item;
       NSInteger to = destinationIndexPath.item;
       //1.获取要删除的数据
       NSString *o = self.datasourceArray[from];    
       //2.删除要移动的数据
       [self.datasourceArray removeObjectAtIndex:from];    
       //3.插入指定的位置
       [self.datasourceArray insertObject:o atIndex:to];
}

sectionInset内边距

dd.png

自定义Layout

  1. 边界改变是否让布局无效
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return YES;
}
  1. 准备布局
/*
 *注释:第一步
 *  1.实例化时最开始调用这个方法,
 *  2.布局无效之后
 *  3.查询布局信息之前
 *  4.如果子类覆盖(重写方法),子类应该总是调用super。invalidateLayout布局无效
 *  5.在这里面一般就是写collectionView、cell。。配置信息(itemSize,间距等)
 */
-(void)prepareLayout
{
    [super prepareLayout];
    //滚动方向
    self.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置collectionView内边距
    CGFloat insert = (self.collectionView.frame.size.width - self.itemSize.width) / 2;
    self.sectionInset = UIEdgeInsetsMake(insert, insert, insert, insert);
}
  1. 返回滚动后推荐的停留点(偏移量)
/*
 *注释:第二步
 *
 *返回滚动后推荐(proposed)停止的点(偏移量),在这里要进行处理
 */
-(CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
{
    //计算最终显示的边界
    CGRect rect;
    rect.origin.x = proposedContentOffset.x;
    rect.origin.y = 0;
    rect.size = self.collectionView.frame.size;
    // 获得所有显示区域内的布局对象
    NSArray *arr = [super layoutAttributesForElementsInRect:rect];
    // collectionView中心点的x值 、 偏移量 + 一半宽度 = 当前collectionView的中点对应着contentView的哪一个中点
    CGFloat contentCenterX = self.collectionView.frame.size.width / 2 + proposedContentOffset.x;
    //存放布局对象数组中离(上面计算的)的点最小间距的布局对象的距离
    CGFloat minDistance = MAXFLOAT;
    for (UICollectionViewLayoutAttributes * attr in arr) {
        CGFloat distance = ABS(attr.center.x - contentCenterX);
        minDistance = minDistance > distance ? distance : minDistance;
    }
    //处理推荐的点,达到每次都停在图片中间的效果(之所以明确是➕,因为偏移一定是负数)
    proposedContentOffset.x += minDistance;
    return proposedContentOffset;
}
  1. 重新布局可视范围视图内的所有子控件
/*
 *注释:第三步:重新布局所有子控件cell
 *
 *作用相当于layoutSubViews,最后才执行的
 */
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    //先布局super,只有流体布局才能使用
    NSArray *arr = [super layoutAttributesForElementsInRect:rect];
    
    //计算contentView中心点
    CGFloat contentCenterX = self.collectionView.contentOffset.x + self.collectionView.frame.size.width / 2;
    
    for (UICollectionViewLayoutAttributes *attr in arr) {
        //求contentView的中心点和cell的中心点的距离[ABS:取绝对值]
        CGFloat distance = ABS(attr.center.x - contentCenterX);//比不理解。。。。。。。。。。。。。。
        //根据间距,计算缩放比例,
        CGFloat scale = 1 - distance / self.collectionView.frame.size.width;
        //设置cell的显示比例(当cell正好处于collectionView中点)
        attr.transform = CGAffineTransformMakeScale(scale, scale);
    }
    return arr;
}

第三方CHTCollectionViewWaterfallLayout的使用

  • 组头、组尾
  • 必须实现的代理方法,确定itemSize
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
  UICollectionReusableView *reusableView = nil;

  if ([kind isEqualToString:CHTCollectionElementKindSectionHeader]) {
    reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                      withReuseIdentifier:HEADER_IDENTIFIER
                                                             forIndexPath:indexPath];
  } else if ([kind isEqualToString:CHTCollectionElementKindSectionFooter]) {
    reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                      withReuseIdentifier:FOOTER_IDENTIFIER
                                                             forIndexPath:indexPath];
  }

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

推荐阅读更多精彩内容