Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sectionForSectionIndexTitle in UITableView iOS

Tags:

ios

tableview

I have just started in ios, and I am stuck with UITableView.

I want to implement index bar in right side of the view. I have implemented this but when I tap on the section on the index bar it's not working.

This is my code. Here indexArray is as "A-Z" element and finalArray is my UITableView mutable array.

Please tell me what should i implement in 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
{

}
like image 408
user1960149 Avatar asked Jan 12 '23 23:01

user1960149


1 Answers

This is perhaps one of the most confusing methods in the UITableViewDataSource, its best to consider an example:

Lets say you have a table view with 4 items:

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

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

You then have 26 section index titles (the index on the right side of the table view): A - Z

Now the user taps on letter 'C' you get a call to

tableView:sectionForSectionIndexTitle:@"C" atIndex:2

You need to return 1 - the section index for the 'C' section.

If the user taps 'Z' you will also have to return 1 since you only have 2 sections and C is the closest to Z.

In the simple case where you have the same sections in your table view as the index on the right had side its ok to do this:

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

Otherwise it depends on your setup. You might have to look for the title in you section titles:

 NSInteger section = [_sectionTitles indexOfObject:title];
 if (section == NSNotFound) // Handle missing section (e.g. return the nearest section to it?)
like image 142
Robert Avatar answered Jan 22 '23 16:01

Robert