Friday, June 7, 2013

UITableView UITableViewIndexSearch example in Objective C (iOS).


UITableView UITableViewIndexSearch

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.
UITableView UITableViewIndexSearch example.
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray* indexTitles = [NSMutableArray arrayWithObject:UITableViewIndexSearch];  // add magnifying glass
    [indexTitles addObjectsFromArray:[self.fetchedResultsController sectionIndexTitles]];
    return indexTitles;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if (title == UITableViewIndexSearch) {
     // if magnifying glass
        [self.resultsTable scrollRectToVisible:self.searchDisplayController.searchBar.frame animated:NO];
     return -1;
    }
    else
     return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index-1];
}

Example of [UITableView UITableViewIndexSearch].
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    if (index==0){
        [tableView scrollRectToVisible:CGRectMake(0,0,1,1) animated:NO];
        return -1;
    }
...
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
        NSMutableArray * retValue =[NSMutableArray arrayWithArray:[YOUR ARRAY]];
        [retValue insertObject:UITableViewIndexSearch atIndex:0];
       return retValue;
 } 

UITableView UITableViewIndexSearch example.
- (NSInteger)tableView:(UITableView *)tv sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    NSInteger section = -1;
    if ([title isEqualToString:UITableViewIndexSearch]) {
        CGRect searchBarFrame = self.searchDisplayController.searchBar.frame;
        [tv scrollRectToVisible:searchBarFrame animated:NO];
    }
    else {
        section = whatever logic you use to determine section
    }
    return section;
}

End of UITableView UITableViewIndexSearch example article.