1碎浇、 collectionView 沒有像tableview那樣自帶索引,所以要自己額外寫個view作索引璃俗。
2奴璃、 索引嘛,就是A B C D然后頭尾加個小圖標(biāo)之類的城豁,所以我決定簡單點:字符部分苟穆,也就是A B C部分用一個豎向的UILabel來搞定,然后在頭或尾根據(jù)需要添加UIImageView;然后兩者放在同一個superView上雳旅。即:
<pre>UIView跟磨,父視圖,用來處理索引的點擊<pre>UIImageView,添加小圖標(biāo)攒盈,比如常用聯(lián)系人抵拘、最熱之類的</pre><pre>UILabel,添加子母標(biāo)簽沦童,如A B C等</pre></pre>
(簡書的markdown可以直接用pre標(biāo)簽仑濒,吊。偷遗。)
3墩瞳、索引是用來點擊然后跳轉(zhuǎn)的,所以最關(guān)鍵的問題是要準(zhǔn)氏豌。所以我把每個標(biāo)識的高度限定成一樣了喉酌,比如19.然后在UIView上添加點擊手勢,在點擊方法里獲取點擊的位置的y值泵喘,根據(jù)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 就是設(shè)定好的,每個標(biāo)識的高度纪铺。取到索引就可以根據(jù)索引跳轉(zhuǎn)collectionView相速,比如你要跳到某個section的開頭,這種應(yīng)該比較常用:
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鲜锚,也有相應(yīng)方法:
- (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 是所有字符索引的數(shù)組蔬捷,在每個之間插入“\n”拼字符串。minimumLineHeight控制一行字符的高度榔袋,alignment讓字符在索引的UIView里居中周拐。最后構(gòu)建NSAttributedString類型字符串給UILabel。搞定凰兑!