iOS

iOS Programming 101: Adding Section and Index List in UITableView


Recently, a reader asked me how to add an index list in a UITableView. As some of you may have the same question, I thought it’s better to write a post to share the solution. An indexed table view is more or less as the plain-styled table view that we’ve covered at the very beginning of our iOS programming course. The only difference is that it includes 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.

If you’ve followed our UITableView tutorial, you should 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.
indexed-uitableview-featured

There’s no better way to explain the implementation than showing an example. As usual, we’ll build a simple app together and you should get a better idea of index list in a minute.

A Brief Look at the Demo App

First, let’s see what we’re going to build for the demo app. 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. The below screenshot displays the final deliverable of the demo app.

indexedtable demo

To work on the tutorial, you’re expected to have basic knowledge of UITableView. If not, stop right here and check out our UITableView tutorial first.

Download the Xcode Project Template

The focus of the tutorial is on the implementation of sections and index list. Therefore, instead of building the Xcode project from scratch, you can download the Xcode project template from here. The template already includes everything you need to start with. If you build the template, you’ll have an app showing a list of animals in table form as shown below.

animal table demo

Later, we’ll modify the app, split the data into sections and add an index list to the table.

Displaying Sections in UITableView

Okay, 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 AnimalTableTableViewController.m:

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

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.

Additionally, we declare the animalSectionTitles array for storing the section titles. For convenience, we simply use the keys of the animals dictionary as the section titles. To get the keys of a NSDictionary, you can simply call the allKeys: method. On top of that, we sort the titles in alphabetical order.

Next, change the numberOfSectionsInTableView: method and return the total number of sections:

To display a header title for each section, we need to implement the titleForHeaderInSection: method. We simply return the section title based on the section index.

It’s very straightforward, right? Next, we have to tell the table view the number of rows for a particular section. Add the numberOfRowsInSection: method in the AnimalTableTableViewController.m:

When the app starts to render the data in the table view, the numberOfRowsInSection: will be called when a new section is displayed. Here based on the section index, we get the section title and use it as a key to retrieve the animal names for the section, followed by returning the total number of the animal names for that section.

We’re almost done. Lastly, modify the cellForRowAtIndexPath: method as follows:

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.

Okay, you’re ready to go! Hit the Run button and you should end up an app like this.

section table demo

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.

That’s it! Compile and run the app again. You should find the index on the right side of the table. Interestingly, you do not need any implementation and the indexing already works! Try to tap any of index and you’ll be brought to a particular section of the table.

animal table with index

Adding A-Z Index List

Look like we’ve done everything. So what’s the sectionForSectionIndexTitle: method for? Presently, 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:

In the viewDidLoad: method, add the following line of code to initialize the section index as “A-Z”:

Next, change the sectionIndexTitlesForTableView: method and return the animalIndexTitles array instead of the animalSectionTitles array.

Now, compile and run the app again. Cool! The app displays the index from A to Z. But wait a minute… It doesn’t work properly. Try to tap the index “C” and the app jumps to the “D” section.

animal table a-z index

Well, as you may notice, the number of indexes is greater than the number of section. The UITableView doesn’t know how to handle the indexing. In this case, you have to implement the sectionForSectionIndexTitle: method and explicitly return the section number when a particular index is tapped. Therefore, add the following lines of code:

Based on the selected index name (i.e. title), we locate the correct section index from the animalSectionTitles. Compile and run the app again. The index list should now work!

Summary

When you need to display a large number of records, it’ll be great to organize the data into sections and provide an index list for easy access. In this tutorial, we’ve walked you through the implementation of indexed table. By now, I believe you should know how to add sections and an index list to your table view.

For your reference, you can download the complete Xcode project from here. As always, leave me comment and share your feedback about the tutorial.

Tutorial
Working with Drag and Drop APIs in iOS 11
iOS
A Beginner’s Guide to Optionals in Swift
iOS
Unable to Set Layout Constraint to Zero in Xcode 11.3
  • John Cruz

    John CruzJohn Cruz

    Author Reply

    great article.


  • Stewart

    StewartStewart

    Author Reply

    Awesome tutorial. I’ve also got a sample using dates from Parse.com (minus index). It works great, although I’m sure there’s more code than necessary 🙂


  • Nic

    NicNic

    Author Reply

    simple demo and great tutorial. This really helps me a lot. I’ve been a loyal reader of this website since I was a beginner and I would love to see more advanced topic like Core data with concurrency. So far, there is no step-by-step or easy-to-understand tutorial about that topic on the internet. I think AppCoda can manage that 🙂


  • Abel

    AbelAbel

    Author Reply

    Excellent example, all your tutorial are great, i have a question or a propose to continue this tutorial.. how to do a round image like all the new design in IOS7, and a detail view..


  • ahmad

    ahmadahmad

    Author Reply

    Guys how can i go from this TableView to DetailView which include different content (in this case description on animals)?


  • Aleem Mohammed

    This is a great tutorial, can you do one on populating a uitableview using an sqlite database?


  • Ahmad

    AhmadAhmad

    Author Reply

    its a great tutorial plz tell me i want when we search something we write the words in search bar the result will display now i want when we enter the space than index 1 result will display on the textview


  • Dan

    DanDan

    Author Reply

    Thanks for writing such a great tutorial!

    I’ve dragged your classes and images into my own xCode project but unfortunately the program is crashing whenever I scroll down the table? It crashes on this line: NSArray *sectionAnimals = [animals objectForKey:sectionTitle]; I get a EXC_BAD_ACCESS error. Any ideas why this is happening? Also, the A to Z index does not appear?


  • Quân Chùa

    youre my life saver…


  • Tiago

    TiagoTiago

    Author Reply

    Same as Dan, i’m getting the same error, when scrolling down or up the program crashes. Please help as i can’t find a solution! Thank you in advance


  • pentool

    pentoolpentool

    Author Reply

    Anyone knows a tut EXACTLY like this, but implemented for core data? It’s a nightmare! I found some posts about this in various stackoverflow posts referring to transient properties and all that. But it seems people keep arguing about that. Some says that’s the way to do it, some says transient properties are nonsense, etc. I’d love to know if this can be implemented without transient properties and if so how.


    • Corey Pett

      Corey PettCorey Pett

      Author Reply

      Still active? I can help you with coreData


  • Abi

    AbiAbi

    Author Reply

    Nice tutorial.
    I have a problem: how could I set the width of the indexList? I’ve country names as section index titles like “Argentina”, or “Burkina Faso” or even longer, and it doesn’t look so good. Any solution to this?


  • Tharaka

    TharakaTharaka

    Author Reply

    great tutorial. sectionForSectionIndexTitle does not work for me…can you help me?


  • Judy

    JudyJudy

    Author Reply

    Do you have a tutorial that is like this but it enhances the data with a detail view when you click on the animal?


  • arbnori224

    arbnori224arbnori224

    Author Reply

    Thanks a lot man, this is the best tutorial ever. simple and useful and not long.


  • Girish Chauhan

    Great article,
    Save my time and anergy
    Thanks a lot


  • stescodes

    stescodesstescodes

    Author Reply

    Great article and thank you for the code. I’m facing one issue, when I select or unselect a row and I scroll down, I can see some of the rows which I didn’t unselect got unselected automatically. How can I fix this issue? please help


  • Prashant Tukadiya

    Very Nice . . . .


  • mp

    mpmp

    Author Reply

    With UILocalizedIndexedCollation.currentCollation().sectionTitles, you can get a localized list of [A – Z]


  • John Martin

    How cna i increase touchable range of alphabets at right side on tableview?


  • Nit

    NitNit

    Author Reply

    how to change the color of that particular index title when i click to any index.


  • Neeraj Joshi

    appcoda always comes with great tutorials, thanx a ton man 🙂


  • Necip Alicikoglu

    is there a way to add subtitles to each animal by any chance?


  • Inno Orikiiriza

    Great article, any links to a demo written in Swift?


  • everSin berserch

    neat!
    how can i change the z-order of the index list? i have a center aligned tableview with center aligned section header labels, which all get offset by introducing the index list. So now i’m figuring out how to fix it and the easiest way would be if i could let the index list hover above the rest of the scene…
    thx for help:)


  • Michael Dobekidis

    Can we have this tutorial for swift?


    • steve

      stevesteve

      Author Reply

      Learn objc. You can’t do ios without knowing it.


      • Michael Dobekidis

        I respectfully disagree. Swift3 is already removing every part that resembles ObjC from Swift. I think a successful company will not maintain both languages. ObjC is outdated, not worth the learning curve and honestly it has no concept of modern programming. So I think I will stick with Swift and try to get better at it. Thanks for the tip, and I know it hurts all ObjC coders (because they went through hell to learn that language) but I think it is time to leave the boat.


  • parth

    parthparth

    Author Reply

    How can i use this code for listing contact of address book? Because some contacts have no name. Only phone number. So how can i manage this?


    • Alfredo Lopez

      Hi,
      You could add a special key to the dictionary; lets call it “#” and if our contact has no name them add them to the array in this section. Hope it helps. 🙂


  • Alfredo Lopez

    Thanks a lot for this tutorial. It’s amazing.
    I added some logic to make the dictionary creation a little bit more dynamic in case anyone is interested 🙂

    – (void)viewDidLoad
    {
    [super viewDidLoad];

    animalsRaw = @[@”Bear”, @”Black Swan”, @”Buffalo”, @”Camel”, @”Cockatoo”, @”Dog”, @”Donkey”, @”Emu”, @”Giraffe”, @”Greater Rhea”, @”Hippopotamus”, @”Horse”, @”Koala”, @”Lion”, @”Llama”, @”Manatus”, @”Meerkat”, @”Panda”, @”Peacock”, @”Pig”, @”Platypus”, @”Polar Bear”, @”Rhinoceros”, @”Seagull”, @”Tasmania Devil”, @”Whale”, @”Whale Shark”, @”Wombat”];

    //go through the animals and create an array.
    NSString *key = [[NSString alloc] init];
    animals = [[NSMutableDictionary alloc] init];

    for (NSString *animal in animalsRaw) {
    //define the key for the animals.
    key = [[animal substringToIndex:1] uppercaseString];

    if ([animals objectForKey: key]) {
    [[animals objectForKey: key] addObject: animal];
    }else{
    //create a new array and add it to the dictionary.
    [animals setObject:[NSMutableArray arrayWithObject: animal] forKey:key];
    }
    }

    animalSectionTittles = [[animals allKeys] sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)];
    }


    • Pratik Shah

      Hi,

      When I try to implement this, I get error “No visible @interface for ‘NSDictionary’ declares the selector ‘setObject:forKey:’

      The error is on this line… “[animals setObject:[NSMutableArray arrayWithObject: animal] forKey:key];”

      Can you suggest what is wrong?


    • Abbas Mulani

      Thank you so much for this reply, it remove unwanted letters from section which does not have data.


  • Yuan

    YuanYuan

    Author Reply

    Its very easy to follow tutorial, Good Job and thank you.


  • Badal Shah

    Badal ShahBadal Shah

    Author Reply

    Complete project link not working. can you please provide new one


  • Saurabh Srivastava

    Sir all thing is good but can we customize index for sectionIndexTitlesForTableView: i mean i want more space between each letter, and even length of item in array more than 50 something like,because if less item we can use some tricks,but it’s not appropriate way. http://stackoverflow.com/questions/18923729/uitableview-section-index-spacing-on-ios-7


  • Dharmesh Kheni

    FInal project isn’t there. Can you please add?


  • Marosdee Uma

    Thanks, it still working on swift 4.


  • Thanh Vo

    Thanh VoThanh Vo

    Author Reply

    Thank you for such a great tutorial.
    I have tried implement this kind of section index list. Everything went fine in most basic case, except for the fact that I can’t find any ways to modify the default behavior of this built-in section index list.
    Apple provided only 4 methods including changing colors and a setting on limit. I have no idea how is everything going behind the scene, and no way to modify that default behavior (adjust size, position, fonts …)

    Or should I use another framework to modify the section index?


Shares