gabaum10
gabaum10

Reputation: 3827

objective-c programmatically change table view from standard to grouped?

The following situation pertains to an iPad app I am working on for my company.

So I have an array of type "Person" that holds the information of a list of people. On the initial page, I have a table that displays their name and picture. When this loads, the results are ungrouped. I was wondering if there was a way to easily group these results with the click of a button based on something like location or business title. The reason they are not grouped when they are loaded is because the powers higher then I deemed it necessary to display the raw list first. Any ideas on doing something like that? Thanks in advance!

Upvotes: 1

Views: 991

Answers (2)

Jasarien
Jasarien

Reputation: 58478

You'll want to use "sections" to split the table.

First you need to sort your datasource into the desired groups, and then reflect it in the view.

A dictionary can easily represent the grouped data. Model each group as an array that contains the entries for that group, and then add it to the dictionary with a key that represents the section.

When the data is ungrouped, you can still use the dictionary, but with a single entry, rather than many, and then reflect that in the UI.

That way when you're asked how many sections there are in the table you can return [dictionary count]; and then when you're asked for the number of rows, you can do something like [[dictionary objectForKey@"myKey"] count];

And so on.

When you've reconfigured your datasource you can call [self.tableView reloadData]; to reload the table with the sections.

Upvotes: 1

Matt Williamson
Matt Williamson

Reputation: 40243

You'll have to remove the UITableView and add another in it's place via [[UITableViewController alloc] initWithStyle:UITableViewStyleGrouped];. You can't change an existing style at runtime.

The other way to do it, is have it grouped from the get-go, but return 1 for - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; if it is "ungrouped" and return all rows for - (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section when it is grouped, do it the normal way.

Upvotes: 1

Related Questions