表视图中的节索引

时间:2010-09-15 22:57:11

标签: iphone

我正在实现一个表索引视图,并惊讶地看到我的表索引如何工作,即使没有实现:

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

我只实施了:

 - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView 

奇怪的是,当我在断点运行时,一旦我点击任何索引值我

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

方法正在被调用。

任何线索为什么会发生这种情况,那么sectionForSectionIndexTitle方法的意义是什么。

2 个答案:

答案 0 :(得分:1)

如果您有一个字母表中的所有字母列表,而您的列表中只包含一些条目,则可以使用以下代码:

//要求数据源返回具有给定标题和节标题索引的节的索引。 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

if (tableView == self.searchDisplayController.searchResultsTableView || self.searchBar.text.length > 0)
{
    return 0;
}
else
{

    //direct - firsttime match
    if([self.realMIndexArray containsObject:title]) {
        NSInteger count = 0;
        for(NSString *character in self.realMIndexArray)
        {
            if([character isEqualToString:title]){
                return count;
            }
            count ++;
        }
    }
    else {

        //take next higher letter from alphabet and check if its contained in the "available letters list"
        //if not, select last entry of list
        for(int i = [self.indexArray indexOfObject:title] + 1; i < [self.indexArray count]; i++) {

            NSString* character = [self.indexArray objectAtIndex:i];

            if([self.realMIndexArray containsObject:character]) {

                return [self.realMIndexArray indexOfObject:character];

            }

        }

        return [self.realMIndexArray count] - 1;

    }
    return 0;// in case of some eror donot crash d application

}

}

realMIndexArray count ==列表中确实存在的字母 indexArray = alphbeth中所有字母的列表。

希望这有助于某人(花了我一点时间来弄清楚)

答案 1 :(得分:0)

  

任何线索为何会发生这种情况

是。当您在表的索引上点击(不点击iPhone)时,基础表视图将要跳转到该部分以及该部分中的单元格。为了做到这一点,它必须向数据源询问这些单元格,以便它可以在屏幕上呈现它们。

  

有什么意义   sectionForSectionIndexTitle方法   然后

tableView:sectionForSectionIndexTitle:atIndex:的文档(这是UITableViewDataSource协议中的可选方法)说:

  

要求数据源返回   具有给定的部分的索引   标题和章节标题索引。

  

您仅为此实现此方法   带有节索引的表视图   list - 只能是表视图   以朴素的风格创造   (UITableViewStylePlain)。

这是否适用于您的UITableView?换句话说,您使用的是分组表视图样式吗?

相关问题