Search code examples
objective-cuitableviewindexingalphabetized

Autogroup UITableView alphabetically


Is there a way to auto group/auto-section my UITableView alphabetically? I have a huge array which is being displayed nicely, but it would be even better if I had the sections like in Contacts.app.

Best
–f


Solution

  • First of All Define sections

    self.sections = [NSArray arrayWithObjects:@"#", @"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", nil];
    

    then

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
       return 27;
    }
    
    - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
    {
       return self.sections;
    }    
    
    - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index
    {
       return index;
    }
    
    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
       return [self.sections objectAtIndex:section];
    }
    

    After that filter by alphabets

    NSArray *sectionArray = [vendorList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", [self.sections objectAtIndex:section]]]; 
                rowCount = [sectionArray count];