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。搞定!