Friday, June 7, 2013

UITableView sectionIndexColor example in Objective C (iOS).


UITableView sectionIndexColor

The color to use for the table view’s index text.

@property(nonatomic, retain) UIColor *sectionIndexColor

Discussion of [UITableView sectionIndexColor]
Table views can display an index along the side of the view, making it easier for users to navigate the contents of the table quickly. This property specifies the color to use for text displayed in this region.

UITableView sectionIndexColor example.
As of iOS 6.0 there are two methods that allow you to change the color of the section indexes and the background shown when you drag the scrubber.

if ([tableView respondsToSelector:@selector(setSectionIndexColor:)]) {
    tableView.sectionIndexColor = ... // some color
    tableView.sectionIndexTrackingBackgroundColor = ... // some other color
}

Example of [UITableView sectionIndexColor].
if ([[self tableView] respondsToSelector:@selector(setSectionIndexColor:)])
{
    // In iOS 6 there is a own method available to set the index color
    [[self tableView] setSectionIndexColor:[UIColor whiteColor]];
}
else
{
    // Use this hack in previous iOS releases
    for(UIView *view in [self.tableView subviews])
    {
        if([view respondsToSelector:@selector(setIndexColor:)])
        {
            [view performSelector:@selector(setIndexColor:) withObject:[UIColor whiteColor]];
        }
    }
}

UITableView sectionIndexColor example.
//iOS 6 devices only
[[self tableView] setSectionIndexColor:[UIColor whiteColor]];

//if targeting devices prior to iOS6 prevent a crash by verifying device OS version
NSArray *versionCompatibility = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
NSInteger OSVersion = [[versionCompatibility objectAtIndex:0] intValue];
if (OSVersion >= 6) {
    [[self tableView] setSectionIndexColor:[UIColor whiteColor]];
}

End of UITableView sectionIndexColor example article.