articles

Home / DeveloperSection / Articles / iOS : Sample of creating Sections in UITableView

iOS : Sample of creating Sections in UITableView

Anonymous User6642 31-Jul-2015

In this article we are going to create a sample using UITableView class, here we use table view property “sections” in table viewcontroller. And also using creating an index on the right side of the table view. Indexed table is very common in iOS apps. The most well-known example is the built-in Contacts app on iPhone. By offering an index scrolling, users are allowed to access a particular section of the table instantly without scrolling through each section.

Here we assume that you know how to implement an UITableView. Basically, to add sections and an index list in the UITableView, you need to deal with these methods as defined in UITableViewDataSource protocol:

  • - numberOfSectionsInTableView: method – returns the total number of sections in the table view. Usually we set the number of section to 1. If you want to have multiple sections, set this value to a larger number.
  • - titleForHeaderInSection: method – returns the header titles for different sections. This method is optional if you do not assign titles for the section.

  • - numberOfRowsInSection: method – returns the total number of rows in a specific section

  • - cellForRowAtIndexPath: method – this method shouldn’t be new to you if you know how to display data in UITableView. It returns the table data for a particular section.

  • - sectionIndexTitlesForTableView: method – returns the indexed titles that appear in the index list on the right side of the table view. For example, you can return an array of strings containing “A” to “Z”.

  • - sectionForSectionIndexTitle: method – returns the section index that the table view should jump to when user taps a particular index.

First, let’s see what we’re doing to build for our sample. It’s a very simple app showing a list of animals in a standard table view. But this time, the app groups the animals into different sections and provides an index list for quick access.

let’s get started and add sections to the table view. Originally, the animal data is stored in an array:

Well, we’re going to organize the data into sections based on the first letter of animal name. There are a lot of ways to do that. But as a demo, we’ll replace the animals array with a NSDictionary. First, declare the animals variable as a NSDictionary and add another array for the section titles in the ViewController.m:

@interfaceViewController (){

    NSDictionary *animals;

    NSArray *animalSectionTitles;

}

@end


In the viewDidLoad: method, change the code to the following:

- (void)viewDidLoad{

    [superviewDidLoad];

/* Do any additional setup after loading the view,

typically from a nib.*/

    animals = @{@"A" : @[@"African Bush Elephant",@"African Wild Dog",

@"Anteater"],

                @"B" : @[@"Bear", @"Black Swan", @"Buffalo"],

                @"C" : @[@"Camel", @"Cockatoo"],

                @"D" : @[@"Dog", @"Donkey"],

                @"E" : @[@"Emu"],

              @"G" : @[@"Giraffe", @"Greater Rhea"],

                @"H" : @[@"Hippopotamus", @"Horse"],

                @"K" : @[@"Koala"],

                @"L" : @[@"Lion", @"Llama"],

                @"M" : @[@"Manatus", @"Meerkat"],

                @"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus",

@"Polar Bear"],

                @"R" : @[@"Rhinoceros"],

                @"S" : @[@"Seagull"],

                @"T" : @[@"Tasmania Devil"],

                @"W" : @[@"Whale", @"Whale Shark", @"Wombat"]};

    // here creating new array list of all keys of animals

    animalSectionTitles=[[animalsallKeys] sortedArrayUsingSelector:

@selector(localizedCaseInsensitiveCompare:)];

}


In the above code, we create a NSDictionary for the animal variable. The first letter of the animal name is used as key. The value that associates with the corresponding key is an array of animal names.

Indexing in TableView:


The indexPath contains the current row number, as well as, the current section index. Again, based on the section index, we retrieve the section title (e.g. “B”) and use it as the key to retrieve the animal names for that section. The rest of the code is very straightforward. We simply get the animal name and set it as the cell label. The getImageFilename: method is a helper method bundled in the project template for handy retrieval of the image file name.

Adding Index List to UITableView

So how can you add an index list to the table view? Again it’s easier than you thought and can be achieved by a few lines of code. Just add the sectionIndexTitlesForTableView: method and return an array of the section indexes. Here we use the section titles as the indexes.

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    returnanimalSectionTitles;

}

Adding A-Z Index List


(You can add A-Z index in the index list but we can't use them in our sample but i will tell you how to displaying them.) The index list doesn’t contain all alphabets. The app just shows those letters that are defined as the keys of the animals dictionary. For some reasons, you may want to display A-Z in the index list. Let’s declare a new variable named animalIndexTitles. The @interface declaration should look like this:

@interfaceViewController (){

    NSDictionary *animals;

    NSArray *animalSectionTitles;

    NSArray *animalIndexTitles;

}

@end


and after modify sectionIndexTitlesForTableView: method like here:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

{

    //return animalSectionTitles;

    return animalIndexTitles;

}


Now, here is our source code:

we can't do any modification in our AppDelegate.h and AppDelegate.m file, only changes will be in ViewController.h and ViewController.m file.

ViewController.h file


#import <UIKit/UIKit.h>

// add UITableViewDelegate and UITableViewDataSource

@interface ViewController : UIViewController <UITableViewDelegate,

UITableViewDataSource>

@end


ViewController.m file


#import "ViewController.h"

@interfaceViewController (){

    NSDictionary *animals;

    NSArray *animalSectionTitles;

    //NSArray *animalIndexTitles;

}

@end

@implementation ViewController

- (void)viewDidLoad {

    [superviewDidLoad];

/* Do any additional setup after loading the view, 

typically from a nib. */  

    animals = @{@"A" : @[@"African Bush Elephant",@"African Wild Dog",

@"Anteater"],

                @"B" : @[@"Bear", @"Black Swan", @"Buffalo"],

                @"C" : @[@"Camel", @"Cockatoo"],

                @"D" : @[@"Dog", @"Donkey"],

                @"E" : @[@"Emu"],

                @"G" : @[@"Giraffe", @"Greater Rhea"],

                @"H" : @[@"Hippopotamus", @"Horse"],

                @"K" : @[@"Koala"],

                @"L" : @[@"Lion", @"Llama"],

                @"M" : @[@"Manatus", @"Meerkat"],

                @"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus"

@"Polar Bear"],

                @"R" : @[@"Rhinoceros"],

                @"S" : @[@"Seagull"],

                @"T" : @[@"Tasmania Devil"],

                @"W" : @[@"Whale", @"Whale Shark", @"Wombat"]};

    // here creating new array list of all keys of animals

    animalSectionTitles=[[animalsallKeys] sortedArrayUsingSelector:

@selector(localizedCaseInsensitiveCompare:)];

    /*animalIndexTitles = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G",

@"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R",

@"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];

}

// table delegate method used to count the no of sections for tables

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return [animalSectionTitlescount];

}

// table delegate method used to get header title for each section

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

    return [animalSectionTitlesobjectAtIndex:section];

}

// table delegate method used to count not of rows for each section

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

    NSString *sectionTitle = [animalSectionTitlesobjectAtIndex:section];

    NSArray *sectionAnimals = [animalsobjectForKey:sectionTitle];

    return [sectionAnimals count];

}

// table delegate method used to set cell in each row with its values

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

    staticNSString *simpleTableIdentifier = @"TableCell";

    NSString *animal = [[animalsobjectForKey:[animalSectionTitles

objectAtIndex:indexPath.section]] 

objectAtIndex:indexPath.row];

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:

simpleTableIdentifier];

    if (cell == nil) {

        cell = [[UITableViewCellalloc] initWithStyle:

UITableViewCellStyleDefaultreuseIdentifier:

simpleTableIdentifier];

    }

    cell.textLabel.text = animal;

    return cell;

}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    returnanimalSectionTitles;

    //return animalIndexTitles;

}

- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

Running our Sample:


Okay, you’re ready to go! Hit the Run button and below displaying final sample app screenshot:

iOS : Sample of creating Sections in UITableView


Updated 07-Sep-2019
I am a content writter !

Leave Comment

Comments

Liked By