Chris
Chris

Reputation: 85

Table View organization into Alphabetical Sections

ok, onto my next dilemma. I've done a ton of Googling and it seems there are several ways to go about it, but none seem to fit my structuring of my table view. I'm using Xcode 4.3.2 with ARC and storyboards. I have a plain view table view. My table consists of a list of cities and their departments (one city for each row), when the user selects a city they will be pushed to a detail view of about that city. I want to organize my table alphabetically, with a section header. Any recommendations, hints, links to tutorials, would be greatly appreciated.

I have a NSMutable array set up like this in my table view .m

NSMutableArray *dept;   

- (void)viewDidLoad

{
[super viewDidLoad];

dept = [[NSMutableArray alloc] init];

City *thedept = [[City alloc] init];
[thedept setCityname:@"Albany"];
[thedept setPhone:@"5551237890"];
[dept addObject:thedept];

thedept = [[City alloc] init];
[thedept setCityname:@"Boston"];
[thedept setPhone:@"5556543435"];
[dept addObject:thedept];

thedept = [[City alloc] init];
[thedept setCityname:@"Springfield"];
[thedept setPhone:@"5553456323"];
[dept addObject:thedept];

thedept = [[City alloc] init];
[thedept setCityname:@"Tallahassee"];
[thedept setPhone:@"5552450988"];
[dept addObject:thedept];

thedept = [[City alloc] init];
[thedept setCityname:@"Vacouver"];
[thedept setPhone:@"5551312555"];
[dept addObject:thedept];

The section header can just be the letter of the alphabet (A, B, C, D...). I'm thinking I need to pre-organize my cities by their first letter and maybe name the section based on the letter (such as "sectionAcities"). The cities I have given are just a few, I have about 100 total.

Upvotes: 0

Views: 1065

Answers (2)

Shreesh Garg
Shreesh Garg

Reputation: 562

In your case you have to use object based sorting using following code instead of simple sorting done in sample

self.tableArray =[[self.tableArray sortedArrayUsingComparator:^NSComparisonResult(Object *first, Object *second){

    NSString *name1=[first name];
    NSString *name2=[second name];
    return [name1 compare:name2];

}]mutableCopy] ;

After this you will get your sorted array and you can use this array to make dictionary of array.

Upvotes: 0

rishi
rishi

Reputation: 11839

You need to use following UITableViewDataSource methods in order to achieve this.

sectionIndexTitlesForTableView:
tableView:titleForHeaderInSection:
tableView:sectionForSectionIndexTitle:atIndex:

Following is link of TheElements app present at that developer.apple.com, which actually do this - http://developer.apple.com/library/ios/#samplecode/TheElements

Upvotes: 1

Related Questions