UITableView iOS中的sectionForSectionIndexTitle

use*_*149 4 tableview ios

我刚刚开始使用ios,而且我很困惑UITableView.

我想在视图的右侧实现索引栏.我已经实现了这个,但当我点击索引栏上的部分时,它无法正常工作.

这是我的代码.这indexArray是"AZ"元素,finalArray是我的UITableView可变数组.

请告诉我应该实施什么sectionForSectionIndexTitle.

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [finalArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:         (NSInteger)section
{
    return [finalArray objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return indexArray;
}

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

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ert 9

这可能是其中最令人困惑的方法之一UITableViewDataSource,最好考虑一个例子:

假设您有一个包含4个项目的表格视图:

section index - 0 section title - 'A' 
items: ['Apple', 'Ant']

section index - 1 section title - 'C'
items: ['Car', 'Cat']
Run Code Online (Sandbox Code Playgroud)

然后你有26个部分索引标题(表视图右侧的索引): A - Z

现在,用户点击字母'C'即可接听电话

tableView:sectionForSectionIndexTitle:@"C" atIndex:2
Run Code Online (Sandbox Code Playgroud)

您需要返回1 - "C"部分的部分索引.

如果用户点击'Z',您还必须返回1,因为您只有2个部分,C最接近Z.

在简单的情况下,您在表视图中具有相同的部分,因为右侧的索引可以执行此操作:

 - (NSInteger)tableView:(UITableView *)tableView 
              sectionForSectionIndexTitle:(NSString *)title 
              atIndex:(NSInteger)index
 {
     return index;
 }
Run Code Online (Sandbox Code Playgroud)

否则取决于您的设置.您可能需要在章节标题中查找标题:

 NSInteger section = [_sectionTitles indexOfObject:title];
 if (section == NSNotFound) // Handle missing section (e.g. return the nearest section to it?)
Run Code Online (Sandbox Code Playgroud)