给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