sectionForSectionIndexTitle in UITableView iOS

4

我刚开始接触iOS,现在遇到了UITableView的问题。

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

这是我的代码。这里的indexArray是"A-Z"元素,而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
{

}

因为你没有返回任何东西,请阅读此链接:https://dev59.com/PE3Sa4cB1Zd3GeqPsiJU,如果不需要该方法,请将其删除。你应该已经准备好了。 - Desdenova
1
谢谢,但是如果我不使用sectionforsectiontitle,并且点击索引栏,什么都不会发生。所以这就是为什么我需要实现它的原因。那么我应该返回什么? - user1960149
1个回答

9

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

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

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

section index - 1 section title - 'C'
items: ['Car', 'Cat']

在表格视图右侧,您将看到26个章节索引标题: A-Z

现在,当用户点击字母'C'时,您会收到一个调用:

tableView:sectionForSectionIndexTitle:@"C" atIndex:2

您需要返回“C”部分的索引号减1。

如果用户点击了“Z”,由于您只有2个部分,且“C”是最接近“Z”的部分,因此您还需要返回1。

在简单情况下,如果您的表视图中的部分与右侧索引相同,则可以这样做:

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

否则,这取决于您的设置。 您可能需要在部分标题中查找标题:
 NSInteger section = [_sectionTitles indexOfObject:title];
 if (section == NSNotFound) // Handle missing section (e.g. return the nearest section to it?)

谢谢,我遇到了同样的问题,按照你的建议返回索引。表视图仅显示可用部分,但索引显示从A到Z的所有字符。更改后,点击其他字符时它会选择最接近的部分。 - Shanmugaraja G

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