UITableView Sections Tutorial

UITableViews can often be the source of a bit of confusion, especially when we start including sections.
In this tutorial we will walk through the steps to create a basic Section’d Table View, in the next tutorial well implement a UINavigationController as well but i’ll save that for later!

Create a new ‘Single View’ application and call it ‘TableViewSections’

Select ‘ViewController.h’ in the column on the left of the Xcode window, now well add the IBOutlets we need.
We’ll be needing an UITableView and an NSMutableArray to hold all the items for our Table View.
Your .h should look like this,

#import

@interface ViewController : UIViewController
{
    IBOutlet UITableView *mainTable;
    NSMutableArray *dataArray;
}
@end

Thats it for the .h now we can move on the ‘ViewController.m’ file.

Select the ‘ViewController.m’ file from the left hand column, just below the .h you just edited.
First of all in the ViewDidLoad method we want to add some items to our ‘dataArray’ so that the table view has something to display.
There are to types of arrays, there is an NSArray which will only let you add items to it once and you can not edit it’s individual items thereafter. There is also an NSMutableArray , which you will notice is what were using today, you can add and remove objects from a NSMutableArray at any time which makes it very flexible and the suitable choice for our project as we are adding multiple sections. In the .m locate:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

After the ‘[super viewDidLoad];’ paste this code:

//Initialize the dataArray
dataArray = [[NSMutableArray alloc] init];

//First section data
NSArray *firstItemsArray = [[NSArray alloc] initWithObjects:@"Item 1", @"Item 2", @"Item 3", nil];
NSDictionary *firstItemsArrayDict = [NSDictionary dictionaryWithObject:firstItemsArray forKey:@"data"];
[dataArray addObject:firstItemsArrayDict];

//Second section data
NSArray *secondItemsArray = [[NSArray alloc] initWithObjects:@"Item 4", @"Item 5", @"Item 6", @"Last Item", nil];
NSDictionary *secondItemsArrayDict = [NSDictionary dictionaryWithObject:secondItemsArray forKey:@"data"];
[dataArray addObject:secondItemsArrayDict];

As you can see we are adding the data to the ‘dataArray’ in two parts, these will eventually become our separate sections in the UITableView. If you wanted a third section simple copy and paste a section and change the object names like so:

NSArray *thirdItemsArray = [[NSArray alloc] initWithObjects:@"Item 4", @"Item 5", @"Item 6", @"Last Item", nil];
NSDictionary *thirdItemsArrayDict = [NSDictionary dictionaryWithObject:thirdItemsArray forKey:@"data"];
[dataArray addObject:thirdItemsArrayDict];

Its up to you how many sections you want just remember to edit all the code accordingly.

Next we need to add all the configuration methods for the Table View.
First we need to tell the table view how many section it can expect to receive, we’ll use a simple array count to return an int.
Copy this code in to the .m:

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

Next we need to tell the table view how many rows in each section it can expect,
Copy this code to the .m:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    //Number of rows it should expect should be based on the section
    NSDictionary *dictionary = [dataArray objectAtIndex:section];
    NSArray *array = [dictionary objectForKey:@"data"];
    return [array count];
}

After that we’ll specify what text we want as the headers for each section,
Copy this code to the .m:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

	if(section == 0)
		return @"Section 1";
        if(section == 1)
		return @"Section 2";
}

And we’ll also add a footer for just the second section,
Copy this code to the .m:

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {

	if(section == 1){
		return @"This is a footer";
    } else {
        return @"";
    }
}

Now we are ready to actually set up our individual cells, this process is fairly straight forward
Add this to the .m:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"data"];
    NSString *cellValue = [array objectAtIndex:indexPath.row];
    cell.textLabel.text = cellValue;

    return cell;
}

The above code simply loops through our ‘dataArray’ and gets the text object for each row and then adds it to the cell. Hard part done! Now I can here you saying, but how do i know which cell the user selected?! Don’t worry, all shall be revealed.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

	//Get the selected country

    NSString *selectedCell = nil;
    NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.section];
    NSArray *array = [dictionary objectForKey:@"data"];
    selectedCell = [array objectAtIndex:indexPath.row];

    NSLog(@"%@", selectedCell);

    [mainTable deselectRowAtIndexPath:indexPath animated:YES];
}

And thats it for the code, you may now relax! Now all we have to do is setup our ViewController.xib
In the bar on the left hand side of the window (beneath ViewController.m) you will find a file called ViewController.xib. Click on it and the Xcode view will change and will show a blank view, looking something like this:

Drag in a Plain Table View from the object library in the bottom right side of the window. When you drag the table over the grey view it will resize to full size so just drop it on the view.

Select the table and then from the Attributes Inspector change the style from Plain to Grouped. Switch to the Connections Inspector and connect the Data source and Delegate to files owner as shown below:

Once you’ve done that select the files owner (Orange cube on the left) and connect ‘mainTable’ to the TableView. Do this by pressing and dragging the little circle next to ‘mainTable’ and dropping it on the UITableView.

Your finished, all thats left now is to select ‘iPhone Simulator’ and Run your project!
Thanks for reading, if you have any issues leave a comment or email me and ill help you as best I can!
Happy Apping!

In the next tutorial we will continue this topic and create a Table View inside a navigation controller.

Grab the Source Code!

Leave a comment