像iOS联系人应用程序一样创建索引

6
我想创建一个类似于iOS联系人应用程序的视图,如下图所示。基本上我想要的是垂直的“ABCDEFG....”字母表,位于图片右侧。当用户点击字符“M”时,我想要获取字符“M”。我该如何实现?是否有任何iOS控件可以提供这个“ABCDEF...”?
谢谢。
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [[NSArray arrayWithObject:UITableViewIndexSearch] arrayByAddingObjectsFromArray:
            [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles]];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if (title == UITableViewIndexSearch)
    {
        CGRect searchBarFrame = self.searchDisplayController.searchBar.frame;
        [tableView scrollRectToVisible:searchBarFrame animated:YES];

        return -1;
    }
    else {
        UILocalizedIndexedCollation *currentCollation = [UILocalizedIndexedCollation currentCollation];
        NSLog(@"selected charecter=%ld",(long)[currentCollation sectionForSectionIndexTitleAtIndex:index]);
        return [currentCollation sectionForSectionIndexTitleAtIndex:index-1];
    }
}

你想创建一个带有索引的自定义UITableView,还是只想呈现内置的联系人选择器? - Fogmeister
我不想创建自定义的表格视图,我只想要位于右侧的ABCDEF...。那个控件叫什么?是联系人选择器吗? - Krunal
你是否有一个包含自己数据的表格视图?或者你是在使用联系人选择器?请解释你想要做什么,否则我们无法理解。你所提到的控件是UITableView的一部分,如果你没有UITableView,那么你就必须从头开始编写整个控件。 - Fogmeister
我只想要突出显示的部分 ABCD...。我有一个自定义的表格视图,不是普通的纯表格视图。是否可以用自定义表格视图创建相同的视图? - Krunal
1
所以,当我问“你想创建一个带索引的自定义UITableView吗?”而你说“不”时,实际上你的意思是“是”。在谷歌上搜索“UITableView index”,有数百个示例。 - Fogmeister
对不起,如果你卡住了,实际上我不知道控件的名称。 - Krunal
1个回答

12

您需要实现这两个方法:

// return list of section titles to display in section index view (e.g. "ABCD...Z#")
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;                                                    
// tell table which section corresponds to section title/index (e.g. "B",1))
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;

使用相应的数据源:

例如,如果您有一个数组,其中包含

`@"Cat", @"Mouse", @"Dog", @"Horse", @"Duck", @"Monkey"`

你需要返回一个数组给sectionIndexTitlesForTableView,例如:

`@[@"C", @"D", @"H", @"M"]`

因为 @"Dog"@"Duck" 对应的是 @"D"@"Mouse"@"Monkey" 对应的是 @"M" 等等。

当然,在 sectionForSectionIndexTitle 中,您需要返回该索引的相应索引。(@"D" 对应 1,@"M" 对应 3 等等。)


我想要完整的 ABCD...,我需要像这样写吗? - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView { return[NSArray arrayWithObjects:@"A", @"B", @"C", @"D", @"D",.... nil]; } 而且如何获取所选字符? - Krunal
是的,没错。要获取前几个字符,你可以自己做(这并不难),或者如果你已经有了一个 NSArrayNSFetchedResultsController,你可以使用 NSPredicate 来获取它们,但我不确定对于 NSArray 是如何实现的,因为我不喜欢这种方法。我喜欢自己做,以便更好地控制。 - Dani Pralea
我已经尝试了这个,我得到了完整的“ABCDE...”,现在当我单击搜索图标时,它没有显示出搜索栏...请查看我在问题中的编辑 - Krunal
我在第一个单元格中没有添加 searchBar,我需要添加吗? - Krunal
哇,其实你不必在单元格中添加搜索栏。UISearchBar 是一个单独使用的东西...算了... - Fogmeister
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接