仿UITableView 对UIColletionView进行改造 - 流式布局

写这篇文章的目的 一个原因是想把在开发中遇到的一些常见的问题通过文章的形式记录和保留 以后可以没事上来看看 一个原因是因为对TableView不能任意随我定制“深恶痛绝” 特意对CollectionView进行改造让他能被我为所欲为 甚至替代UITableView
代码地址 https://github.com/evernoteHW/UICollectionViewLayoutDemo/tree/master/UICollectionViewLayoutDemo
简单描述下我的思路 方便剁手党 特意贴出代码

1 利用Runtime机制扩展属性

创建UICollectionView 类目 Category 添加两个属性headerView和footerView

- (UIView *)hw_collectionHeaderView
{
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setHw_collectionHeaderView:(UIView *)hw_collectionHeaderView
{
    [self.hw_collectionHeaderView removeFromSuperview];
    objc_setAssociatedObject(self, @selector(hw_collectionHeaderView), hw_collectionHeaderView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addSubview:hw_collectionHeaderView];
    [self.collectionViewLayout invalidateLayout];
}
- (UIView *)hw_collectionFooterView
{
    return objc_getAssociatedObject(self, _cmd);
}
- (void)setHw_collectionFooterView:(UIView *)hw_collectionFooterView
{
    [self.hw_collectionFooterView removeFromSuperview];
    objc_setAssociatedObject(self, @selector(hw_collectionFooterView), hw_collectionFooterView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self addSubview:hw_collectionFooterView];
    [self.collectionViewLayout invalidateLayout];
}

2 子类化 SubClass UICollectionViewLayout

第一步 改写prepareLayout </br>

第一小步 设定Item大小

for (NSInteger item = 0; item < itemCount; item++) {
            
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:item inSection:section];
    UICollectionViewLayoutAttributes *itemAttributes =
    [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    CGFloat item_x = self.itemInsets.left;
    CGFloat item_y = top + itemHeight + self.itemInsets.top;
    CGFloat item_width = self.itemSize.width - self.itemInsets.left - self.itemInsets.right;
    CGFloat item_height = self.itemSize.height - self.itemInsets.top - self.itemInsets.bottom;
    
    itemAttributes.frame = CGRectMake(item_x,item_y, item_width, item_height);
    cellLayoutInfo[indexPath] = itemAttributes;
    
    itemHeight += (self.itemSize.height);
}
        

第二小步 设定Header大小

    NSIndexPath *headerIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
    UICollectionViewLayoutAttributes *headerAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:HWCollectionElementKindSectionHeader withIndexPath:headerIndexPath];
    CGFloat headerHeight = self.headerHeight;
    if ([self.layoutDelegate respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]) {
        headerHeight = [self.layoutDelegate collectionView:self.collectionView layout:self referenceSizeForHeaderInSection:section];
    }
        
    headerAttributes.frame = CGRectMake(0, top, self.itemSize.width, headerHeight);
    headerLayoutInfo[headerIndexPath] = headerAttributes;
    top += headerHeight;
        

第三小步 设定Footer大小

NSIndexPath *footerIndexPath = [NSIndexPath indexPathForItem:itemCount - 1 inSection:section];
UICollectionViewLayoutAttributes *footerAttributes = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:HWCollectionElementKindSectionFooter withIndexPath:footerIndexPath];
    
CGFloat footerHeight = self.footerHeight;
if ([self.layoutDelegate respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]) {
    footerHeight = [self.layoutDelegate collectionView:self.collectionView layout:self referenceSizeForFooterInSection:section];
}
    
footerAttributes.frame = CGRectMake(0, top, self.itemSize.width, footerHeight);
footerLayoutInfo[footerIndexPath] = footerAttributes;
    
top += footerHeight;

第四小步 设定 装饰视图(用处:设定组与组的背景) 这个比较特殊或者分割线 比如类似这样的 组的背景可能是个图片可能组头视图和组所有的cell公用一个背景图 这个比较特殊

NSIndexPath *decorationIndexPath = [NSIndexPath indexPathForItem:0 inSection:section];
UICollectionViewLayoutAttributes *decorationAttributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:HWCollectionElementKindSectionDecoration withIndexPath:decorationIndexPath];
CGFloat decorationHeight = CGRectGetMaxY(footerAttributes.frame) - CGRectGetMinY(headerAttributes.frame);
decorationAttributes.frame = CGRectMake(0, CGRectGetMinY(headerAttributes.frame), self.itemSize.width, decorationHeight);
decorationAttributes.zIndex = -1;
decorationLayoutInfo[decorationIndexPath] = decorationAttributes;
        

这里需要说明的是 zIndex = -1 总是处于最底端

第五小步 确定collectionHeaderView和collectionFooterView 位置
和普通的组头部不同 这个可以类似对比UITableView的tableHeaderView和tableFooterView 也很简单 如下
collectionHeaderView

CGFloat top = 0.0;   
    if (self.collectionView.hw_collectionHeaderView) {
    top += self.collectionView.hw_collectionHeaderView.bounds.size.height;
}

CollectionFooterView

if (self.collectionView.hw_collectionFooterView) {
    self.collectionView.hw_collectionFooterView.frame = CGRectMake(self.collectionView.hw_collectionFooterView.frame.origin.x, top , self.collectionView.hw_collectionFooterView.frame.size.width, self.collectionView.hw_collectionFooterView.frame.size.height)
    ;
    top += self.collectionView.hw_collectionFooterView.bounds.size.height;
}
    

第六小步 将设定的大小全部存储起来
我和别人的比较特殊很多使用二位数组的方式 我是用字典 字典这样的存储方式的好处是我可以任意添加一个Kind类型 然后设置对于的Attribute大小 在任何地方加入都可以 最好存起来 还有一个好处是会在下面的 layoutAttributesForElementsInRect中体现出来

 newLayoutInfo[HWLayoutItemCellKind] = cellLayoutInfo;
 newLayoutInfo[HWLayoutHeaderKind] = headerLayoutInfo;
 newLayoutInfo[HWLayoutFooterKind] = footerLayoutInfo;
 newLayoutInfo[HWLayoutDecorationKind] = decorationLayoutInfo;   
 self.layoutInfo = newLayoutInfo;

第二步 确定在Rect范围内返回的Attribute数组 </br>

第二个好处是 这个方法是通用的不管你PrePareLayout方法怎么干 这些都一成不变的 这个方法的含义是在Rect范围内 意思是说 只是返回Recf范围内的Attribute数组 不是所有的 这个注意一下

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [NSMutableArray arrayWithCapacity:self.layoutInfo.count];
    
    [self.layoutInfo enumerateKeysAndObjectsUsingBlock:^(NSString *elementIdentifier,
                                                         NSDictionary *elementsInfo,
                                                         BOOL *stop) {
        [elementsInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath,
                                                          UICollectionViewLayoutAttributes *attributes,
                                                          BOOL *innerStop) {
            if (CGRectIntersectsRect(rect, attributes.frame)) {
                [allAttributes addObject:attributes];
            }
        }];
    }];
    return allAttributes;
}

第三步 确定 collectionViewContentSize </br>

之前设定的 第三个好处是 我再取得 collectionViewContentSize 取得最后一个Attribute 拿到 CGRectGetMaxY 如果有我之前通过类目方法扩展的collectionHeaderView 做一个判断即可


- (CGSize)collectionViewContentSize
{
    NSInteger sectionCount = [self.collectionView numberOfSections];
    if (sectionCount <= 0) return [super collectionViewContentSize];
    NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:sectionCount - 1];
    
    UICollectionViewLayoutAttributes *footAttributes = nil;
    NSDictionary *dic = self.layoutInfo[HWLayoutFooterKind];
    if (dic.count > 0) {
        footAttributes = self.layoutInfo[HWLayoutFooterKind][[NSIndexPath indexPathForRow:numberOfItemsInSection - 1 inSection:sectionCount - 1]];
    }else{
        footAttributes = self.layoutInfo[HWLayoutItemCellKind][[NSIndexPath indexPathForRow:numberOfItemsInSection - 1 inSection:sectionCount - 1]];
    
    }
    CGFloat height = CGRectGetMaxY(footAttributes.frame);
    if (self.collectionView.hw_collectionFooterView) {
        height += CGRectGetHeight(self.collectionView.hw_collectionFooterView.frame);
    }
    
    return CGSizeMake(self.collectionView.bounds.size.width, height);
}

第四步 设定Layout代理 改装外部可以控制 </br>

设定代理 代理方法如下 当如你如果是比如固定大小的可以通过设定诸如


@property (nonatomic) UIEdgeInsets itemInsets;
@property (nonatomic) CGSize itemSize;
@property (nonatomic) CGFloat interItemSpacingY;
@property (nonatomic) NSInteger numberOfColumns;
@property (nonatomic, assign) CGFloat headerHeight;
@property (nonatomic, assign) CGFloat footerHeight;


也可以通过设定代理随意定制

@protocol HWCollectionViewWaterfallLayoutDelegate <NSObject>
@optional
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section;
//组与组的最小距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section;
//组头高度
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
//组尾高度
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(HWCollectionViewWaterfallLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
@end

End ----

项目效果图

image.png

至此所有的工作都做完了
注意: 我这个只是针对TableView的仿造还没有对流式布局进行进一步处理 下一篇文章说明 如何定制 比如苹果自带浏览器图片等功能 有什么问题可以私信我或者在在下面评论 如果还不错给个Star吧

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

推荐阅读更多精彩内容

  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 3,773评论 1 22
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,136评论 11 349
  • { 24、Sqlite数据库 1、存储大数据量,增删改查,常见管理系统:Oracle、MSSQLServer、DB...
    CYC666阅读 921评论 0 1
  • 用心对生 过往烟云,如风消散 恍世浮华,一生双影 芸芸众生,寻寻觅觅 只为回头,灯火阑珊。
    芈密阅读 134评论 0 0
  • 连续几天都做梦了,早上醒来,躺在床上梦清清楚楚的,很想把梦境记下来,但往往一通忙乎之后,拿起手机要记录的时候,脑海...
    牧田麻麻阅读 166评论 0 0