Reputation: 33
I am writing an iPhone application and I have a table view that is populated by information I feed it from txt files. I would like to group the tables (so like by name for contacts), however I would like to choose which fields go in which grouping.
For instance, for my app, I want to group ingredients by type (so dairy products, produce, etc...) and have the corresponding ingredients appear there. How would I do that? I have this code currently for my table view:
NSString *wellBalancedIngredientFileContents = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Well Balanced Ingredients" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];
wellBalancedIngredients = [wellBalancedIngredientFileContents componentsSeparatedByString:@"(penguins)"];
wellBalancedIngredients (as one of the arrays) is an array that will contain all of the "well balanced ingredients". I have 3 other arrays that I also populate the tableview with depending on user choice.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (ingredientListChoice == 1) {
return [self.wellBalancedIngredients count];
}
else if (ingredientListChoice == 2) {
return [self.meatIngredients count];
}
else if (ingredientListChoice == 3) {
return [self.vegetarianIngredients count];
}
else {
return [self.veganIngredients count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (ingredientListChoice == 1) {
cell.textLabel.text = [self.wellBalancedIngredients objectAtIndex:indexPath.row];
}
else if (ingredientListChoice == 2) {
cell.textLabel.text = [self.meatIngredients objectAtIndex:indexPath.row];
}
else if (ingredientListChoice == 3) {
cell.textLabel.text = [self.vegetarianIngredients objectAtIndex:indexPath.row];
}
else {
cell.textLabel.text = [self.veganIngredients objectAtIndex:indexPath.row];
}
return cell;
// Configure the cell...
}
How do I add to this code to add the grouping into sections and then being able to have custom headings and me populating each section according to my chosen preference. Thank you for your help.
Upvotes: 1
Views: 2030
Reputation: 2200
First, you should return the number of sections you want in the table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return numberOfSections;
}
Then, for the title of each section you can use:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return @"Section Title";
}
Upvotes: 1