Grouped table view is an extension of the normal table view in iPhone. It displayes the data in several sectioned lists. Each section has a header and number of rows associated with it. Examples of grouped table are the ‘contacts’ list, a dictionary,etc. In this tutorial, we will create a grouped table using a dictionary, to create a names list,unlike the plain table in which we had used an array. So lets get started!
Step 1: Create a view based application and name it ‘GroupedTable’.
Step 2: Put the following code in ‘GroupedTableViewController.h’
Here, we have declared a dictionary to hold the section headers and their respective row contents. And an array to hold the sorted keys of the dictionary.
Step 3: Now, open ‘GroupedTableViewController.m’ file and put the following code in it.
viewdidLoad: Here, we populate the dictionary using three arrays of names as objects and alphabets as keys. Then we sort the array ‘allKeys’ of the dictionary and put it in sortedKeys.
Table MethodsNumberOfSectionsInTableView : Returns the count of keys in the dictionary.
titleForHeaderInSection : Returns the value of key for that particular section.
cellForRowAtIndexPath : Here, listdata is an array which is assigned the value for the key corresponding to the respective section. For every section, the contents of listdata are displayed.
didSelectRowAtIndexPath : In this method, we display an alert view when a row is selected.
Step 4 : Open the ‘GroupedTableViewController.xib’. Drag and drop a table view on it. Select the table view and open its Attributes Inspector (command+1). Change the table style from ‘Plain’ to ‘Grouped’.
Step 6 : You can download the source code here in cinterviews
Save,build and run the project. The output will be as follows: