Search code examples
iphonexcodeuitableviewsectionheader

Alphabetically sorting the contacts inside a Section header in a UItableview


I have an issue of alphabetically sorting the contacts picked from the address book into section headers . I can arrange them alphabetically without the section headers but how to put them according to the names of the contacts ? I do not want to use the NSDictionary as I am able to do the sorting without it. Please view the code below :-

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

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[alphabets sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return [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];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{    
    return [arrayForLastName count];
}

Any help would be appreciated thanx :)


Solution

  • You can achieve this in following way -

    1.Create an index array that contains all the required index -

    NSArray *indexArray = [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];
    

    2.For Each index you need to have an array that will display row for those sections. SO you can have a dictionary that contain an array corresponding to each index.

    Check this tutorial, it will help you in implementing this- http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/