使用CSStickyHeaderFlowLayout实现头部固定的CollectionView
近期流行的一种界面效果,是瀑布流的header固定,也叫sticky header或者parallax。对于UITableView,能够比較方便地让table header固定,可是对于UICollectionView,原生的iOS API比較难以实现。
本文推荐一个开源组件。专门用于实现这样的效果:CSStickyHeaderFlowLayout
总体效果
贴个总体示意图
配合autolayout使用
首先须要注意的是,这个组件必须配合autolayout来使用。比方整个header分为4个部分。我想固定的是当中以下的2个subview,一開始我的代码是写死这2个subview的坐标
UILabel *header1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 375, 50)];
header1.backgroundColor = [UIColor yellowColor];
header1.text = @"1111";
UILabel *header2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 50, 375, 50)];
header2.backgroundColor = [UIColor blueColor];
header2.text = @"2222";
这样的话就无法获得预期的效果,由于尽管整个Supplementary的height缩小了,可是subview的坐标却是固定的,所以不会随着header被推到顶部。正确的做法是使用autolayout。我这里用的是masonry
UILabel *header1 = [UILabel new];
header1.backgroundColor = [UIColor yellowColor];
header1.text = @"1111";
UILabel *header2 = [UILabel new];
header2.backgroundColor = [UIColor blueColor];
header2.text = @"2222";
[self addSubview:header1];
[self addSubview:header2];
[header1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(header2.mas_top);
make.left.equalTo(@0);
make.height.equalTo(@50);
make.width.equalTo(@375);
}];
[header2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(@0);
make.left.equalTo(@0);
make.height.equalTo(@50);
make.width.equalTo(@375);
}];
切换cell类型时,注意处理offset
当切换“投票”和“排行榜”的时候。并没有替换Layout,可是切换了不同的cell实现,所以2边的contentOffset是不同的,有可能出现某一组cell已经向下滚动了非常多。而另外一组cell在这个位置上无法正确的显示。处理的办法是,假设offset已经超过某个值。则滚动到顶部
// 假设已经超过顶部,则滚动到顶部
if(myView.contentOffset.y >= 70){
[myView setContentOffset:CGPointMake(0, 70)];
}
与MJRefresh的冲突解决
MJRefresh是还有一个流行的下拉刷新组件。当CSStickyHeaderFlowLayout和它一起使用的时候,在下拉刷新时会出现2次奇怪的动画效果。原因是MJRefresh的实现是改动了UICollectionView的contentInset。而CSStickyHeaderFlowLayout在0.2.7版本号没有正确处理这样的情况。作者已经在0.2.8修复了此问题。issue的详细现象和处理过程在ghost image issue#85
最新文章
- React之Froms
- MySQL 性能优化的最佳20多条经验分享
- android 入门-ID
- React Native ——实现一个简单的抓取github上的项目数据列表
- Spring Mvc 在非controller层 实现获取request对象
- UVa133.The Dole Queue
- Mahout学习路线图
- php 关于经纬度距离计算方法
- Hdu 1022 Train Problem I 栈
- HTML5的自定义属性的使用总结
- 2java判断素数
- pycharm 下的djiango使用
- unhandledException
- 小米路由Mini刷Breed, 潘多拉和LEDE
- Batch Normalization 学习笔记
- mysql概要(二)类型(数值型,字符型,时间类型
- virtualbox安装增强功能并设置共享文件夹
- 应输入 #endregion 指令报错的排查技巧
- Vue使用echarts
- Github:在Github上创建自己的代码仓库