Tuesday, January 13, 2015

Hide UITableView index of empty sections iOS

In iOS, we use "UILocalizedIndexedCollation" to partition music library song objects into sections to display them in table view. The "sectionTitles" array of "currentCollation" instance contains all letters in alphabet from A to Z if our system preferred language is English.

UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
NSArray *sectionTitles = [collation sectionTitles];

Sometimes, due to lack of song titles which begin with certain letters, we have empty sections. For the sake of redundancy, we don't want display their titles and indexes in table view.

To hide them, we could declare a NSMutableArray to store those sections which are not empty:

// declare this in @interface
@property (nonatomic, strong) NSMutableArray *sectionIndexTitles;

// put this snippet in objects partition function
int i = 0;
for (NSMutableArray *section in unsortedSections) {
    if ([section count] != 0) {
        [sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
        [self.sectionIndexTitles addObject:[[collation sectionIndexTitles] objectAtIndex:i]];

Finally we set up the table view delegate methods by using our "sectionIndexTitles":

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sectionIndexTitles count];

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return [self.sectionIndexTitles objectAtIndex:section];

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.sectionIndexTitles;

// touching the index jump to corresponding section
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return [self.sectionIndexTitles indexOfObject:title];

Read this article to know how to configure UITableView by UILocalizedIndexedCollation.

No comments:

Post a Comment