首页 > Web开发 > 详细

使用CSStickyHeaderFlowLayout实现头部固定的CollectionView

时间:2017-06-29 09:14:56      阅读:252      评论:0      收藏:0      [点我收藏+]

近期流行的一种界面效果,是瀑布流的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

使用CSStickyHeaderFlowLayout实现头部固定的CollectionView

原文:http://www.cnblogs.com/mfmdaoyou/p/7092583.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!