Uitableview 表视图标题索引

Uitableview 表视图标题索引,uitableview,indexing,alphabetical,Uitableview,Indexing,Alphabetical,我已经设置了所有的表视图,我可以使用节索引跳转到按字母顺序排列的行,但我希望表视图的标题与设备联系人列表中的标题相同。例如: A Aeroplane B Bike Bus C Car 以下是我到目前为止的情况: - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @

我已经设置了所有的表视图,我可以使用节索引跳转到按字母顺序排列的行,但我希望表视图的标题与设备联系人列表中的标题相同。例如:

A
Aeroplane

B
Bike
Bus

C
Car
以下是我到目前为止的情况:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

NSInteger newRow = [self indexForFirstChar:title inArray:self.Make];
NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:newRow inSection:0];
[tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];

return index;
}

您可以使用从轻松完成此操作。您可以使用基于块的初始值设定项根据每个make的第一个字母将项目组织到各个部分:

NSArray *makes = ...; // array of makes
TLIndexPathDataModel *dataModel = [[TLIndexPathDataModel alloc] initWithItems:makes sectionNameBlock:^NSString *(id item) {
    // assuming the items are NSStrings
    return [((NSString *)item) substringToIndex:1];
} identifierBlock:nil];
然后,索引数据源方法如下所示:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [self.dataModel sectionNames];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    return [self.dataModel sectionForSectionName:title];
}
数据模型API还可以简化其他数据源和委托方法:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataModel.numberOfSections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataModel numberOfRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = ...;
    UITableViewCell *cell = ...; // dequeue cell
    NSString *make = [self.dataModel itemAtIndexPath:indexPath];
    ... // configure cell
    return cell;
}
通过运行可以看到一个工作示例(不过为了简单起见,它使用了一些附加的TLIndexPathTools组件,
TLTableViewController
TLIndexPathController