使用CSStickyHeaderFlowLayout实现头部固定的CollectionView

近期流行的一种界面效果,是瀑布流的header固定,也叫sticky header或者parallax。对于UITableView,能够比較方便地让table header固定,可是对于UICollectionView,原生的iOS API比較难以实现。

本文推荐一个开源组件。专门用于实现这样的效果:CSStickyHeaderFlowLayout

总体效果

贴个总体示意图

sticky header

配合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

转载于:https://www.cnblogs.com/mfmdaoyou/p/7092583.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值