Friday, February 3, 2012

How to Get Magnifying Glass into UITableView Index

If your app contains a list, you might want to considere adding an index bar at right side of the screen. If your list supports search, you might want to add a magnifying glass at top of the index (similar to built-in Contacts application).

Ok, so how do you do that?

Good news is that it's really simple - as soon as you figure it out once. Check Apple iOS SDK for UITableView Class Rerefence and you'll find:

Section Index Icons
Requests icon to be shown in the section index of a table view.
UIKIT_EXTERN NSString *const UITableViewIndexSearch;

Constants
UITableViewIndexSearch

    If the data source includes this constant string in the array of strings it returns in sectionIndexTitlesForTableView:, the section index displays a magnifying glass icon at the corresponding index location. This location should generally be the first title in the index.

    Available in iOS 3.0 and later.

Declared In
UITableView.h
Basically you need to define two methods:
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *indexList =
        [NSMutableArray arrayWithCapacity:[self.otherList count]+1];
    [indexList addObject:UITableViewIndexSearch];
    for (NSString *item in self.otherList)
        [indexList addObject:[item substringToIndex:1]];
    return indexList;
}

- (NSInteger) tableView:(UITableView *)tableView
    sectionForSectionIndexTitle:(NSString *)title
    atIndex:(NSInteger)index
{
    if (index == 0)
    {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    return index - 1; // due magnifying glass icon
}
Easy, right? Now try to use that when app supports screen rotation :) Yes, I've done it as you can see in FontType. Sorry, not going to cover that now. Still not 100% sure I've got it completely right in all possible cases e.g. whether app displays search results vs. not, going into and returning from details view while screen rotates in between etc.

But at least you now got the magnifying glass icon. Best of all, it's defined in SDK and thus future compatible!

2 comments:

  1. I am just finishing an app that will end up having a growing list of media for the users after they add items. And I didn't even think of adding this feature. Thanks for mentioning it it really does help when you have a lot to sift thru.

    ReplyDelete
  2. Heh, I've been saving this article almost a year and was very close to never release it. Too obvious, once you hear about it! Happy I could help not only in technical, but also on design side :)

    ReplyDelete