我有类似的要求(对于水平集合视图)并最终自己构建了一个索引视图子类。
我计划开源它,但可能要等到下个月,所以这里有一个存根让你开始:
YMCollectionIndexView.h
@interface YMCollectionIndexView : UIControl
- (id) initWithFrame:(CGRect)frame indexTitles:(NSArray *)indexTitles;
// Model
@property (strong, nonatomic) NSArray *indexTitles; // NSString
@property (readonly, nonatomic) NSUInteger currentIndex;
- (NSString *)currentIndexTitle;
@end
YMCollectionIndexView.m
#import "YMCollectionIndexView.h"
@interface YMCollectionIndexView ()
@property (readwrite, nonatomic) NSUInteger currentIndex;
@property (strong, nonatomic) NSArray *indexLabels;
@end
@implementation YMCollectionIndexView
- (id) initWithFrame:(CGRect)frame indexTitles:(NSArray *)indexTitles {
self = [super initWithFrame:frame];
if (self) {
self.indexTitles = indexTitles;
self.currentIndex = 0;
// add pan recognizer
}
return self;
}
- (void)setIndexTitles:(NSArray *)indexTitles {
if (_indexTitles == indexTitles) return;
_indexTitles = indexTitles;
[self.indexLabels makeObjectsPerformSelector:@selector(removeFromSuperview)];
[self buildIndexLabels];
}
- (NSString *)currentIndexTitle {
return self.indexTitles[self.currentIndex];
}
#pragma mark - Subviews
- (void) buildIndexLabels {
CGFloat cumulativeItemWidth = 0.0; // or height in your (vertical) case
for (NSString *indexTitle in self.indexTitles) {
// build and add label
// add tap recognizer
}
self.indexLabels = indexLabels;
}
#pragma mark - Gestures
- (void) handleTap:(UITapGestureRecognizer*)recognizer {
NSString *indexTitle = ((UILabel *)recognizer.view).text;
self.currentIndex = [self.indexTitles indexOfObject:indexTitle];
[self sendActionsForControlEvents:UIControlEventTouchUpInside];
}
// similarly for pan recognizer
@end
在您的视图控制器中:
- (void)viewDidLoad {
[super viewDidLoad];
[self.collectionIndexView addTarget:self action:@selector(indexWasTapped:) forControlEvents:UIControlEventTouchUpInside];
// similarly for pan recognizer
}
- (void)indexWasTapped:(id)sender {
[self.collectionView scrollToIndexPath:...];
}
// similarly for pan recognizer