用于UICollectionView的SectionIndexTitles

abi*_*son 21 ios ios5 ios6 uicollectionview

所以我TableView用搜索功能实现了一个正确的sectionIndexTitles.现在,我正在尝试实现一个UICollectionView它到目前为止工作,除了我不能轻易拥有sectionIndexTitles(右滚动条).

如果我查看Facebook应用程序,它看起来像一个UICollectionView,但确实sectionIndexTitles和一个搜索栏.我似乎无法为UICollectionView模型找到这样的功能.

有任何想法吗?!

谢谢!

在此输入图像描述

Yan*_*yer 16

我有一个类似的要求(对于水平集合视图)并最终自己构建索引视图子类.

我打算开源,但可能要等到下个月,所以这里有一个存根来启动你:

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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

在您的视图控制器中:

- (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
Run Code Online (Sandbox Code Playgroud)

  • 我已经在[这里的要点](https://gist.github.com/kreeger/4756030)中完成了一个完整的实现(带有写入) - 让我知道你的想法. (3认同)