使用CSStickyHeaderFlowLayout實現頭部固定的CollectionView

來源:互聯網
上載者:User

標籤:height   number   print   asc   沒有   開源   tle   init   UI   

近期流行的一種介面效果,是瀑布流的header固定,也叫sticky header或者parallax。對於UITableView,能夠比較方便地讓table header固定,可是對於UICollectionView,原生的iOS API比較難以實現。

本文推薦一個開源組件。專門用於實現這樣的效果:CSStickyHeaderFlowLayout

總體效果

貼個總體

配合autolayout使用

首先須要注意的是,這個組件必須配合autolayout來使用。比方整個header分為4個部分。我想固定的是當中以下的2個subview,一開始My Code是寫死這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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.