給CollectionView添加索引

1、 collectionView 沒有像tableview那樣自帶索引,所以要自己額外寫個view作索引。
2、 索引嘛,就是A B C D然后頭尾加個小圖標之類的,所以我決定簡單點:字符部分,也就是A B C部分用一個豎向的UILabel來搞定,然后在頭或尾根據需要添加UIImageView;然后兩者放在同一個superView上。即:
<pre>UIView,父視圖,用來處理索引的點擊<pre>UIImageView,添加小圖標,比如常用聯系人、最熱之類的</pre><pre>UILabel,添加子母標簽,如A B C等</pre></pre>
(簡書的markdown可以直接用pre標簽,吊。。)

3、索引是用來點擊然后跳轉的,所以最關鍵的問題是要準。所以我把每個標識的高度限定成一樣了,比如19.然后在UIView上添加點擊手勢,在點擊方法里獲取點擊的位置的y值,根據y值求是第幾個索引。

-(void)clickStarIndexView:(UITapGestureRecognizer*)tap{
    CGPoint location = [tap locationInView:_starIndexView];
    NSInteger index = location.y / indexTitleHeight ;
    
    if (index == 0) {
        [_collectionView setContentOffset:CGPointZero animated:NO];
        return;
    }
}

indexTitleHeight 就是設定好的,每個標識的高度。取到索引就可以根據索引跳轉collectionView,比如你要跳到某個section的開頭,這種應該比較常用:

destinationRect = [_collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForRow:0 inSection:index]].frame;
CGFloat offsetY = MIN(destinationRect.origin.y, _collectionView.contentSize.height - _collectionView.frame.size.height);
    [_collectionView setContentOffset:CGPointMake(0, offsetY) animated:NO];

如果是某個cell,也有相應方法:

 - (nullable UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath;

4、最后UILabel部分的文字是豎向的,為了方便就直接把UILabel的寬縮小,然后把字符串變成“A\nB\nC...”這樣,每一行就只有一個字符;然后怎么控制每個字符的高度呢?

    NSString *indexesString = [_starIndexTitles componentsJoinedByString:@"\n"];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.minimumLineHeight = indexTitleHeight;
    paragraphStyle.alignment = NSTextAlignmentCenter;
    NSAttributedString *attriString = [[NSAttributedString alloc] initWithString:indexesString   attributes:@{ NSParagraphStyleAttributeName : paragraphStyle, NSForegroundColorAttributeName :textColor ,NSBaselineOffsetAttributeName:@(1)}];
    _charIndexView.attributedText = attriString;

_starIndexTitles 是所有字符索引的數組,在每個之間插入“\n”拼字符串。minimumLineHeight控制一行字符的高度,alignment讓字符在索引的UIView里居中。最后構建NSAttributedString類型字符串給UILabel。搞定!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 發現 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,252評論 4 61
  • API API(Application Programming Interface,應用程序編程接口)是一些預先定...
    知行社閱讀 1,404評論 0 2
  • 關鍵詞:開學啦、傷心、開心、考試、班級、學校、裝修、環境、打掃。 今天我開學了,我早早的來到學校,因為我想...
    帥氣的黃子陽閱讀 173評論 3 5
  • 題記: 這半年來看過許多電影,而沒有一部電影像今天這部讓我一邊笑得岔氣一邊淚流滿面。走過青春的人回望這段無聊懵懂的...
    盧語閱讀 1,284評論 2 4