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.
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.