UITableView 类似通讯录的索引

有时候我们需要实现类似通讯录的索引功能,如果我们自己实现的话,可能要写一些代码。

其实UITableView自己是实现了的,只是默认不显示而已,如下图所示


如果想要右边的字母表,和顶部的字母A显示出来,我们只需要实现UITableViewDataSource 和 UITableViewDelegate的如下两个方法

- (NSString *)tableView:(UITableView *)tableView 

titleForHeaderInSection:(NSInteger)section

{

    if ([keys count] == 0)

        return nil;

    NSString *key = [keys objectAtIndex:section];

扫描二维码关注公众号,回复: 1529477 查看本文章

    if (key == UITableViewIndexSearch)///右侧搜索图标

        return nil;

    

    return key;///即上图中,我们要显示的A

}


- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView

{

    if (isSearching)

        return nil;

    return keys;///右侧字母表和搜索图标

}

///点击右侧字母表调用的方法

- (NSInteger)tableView:(UITableView *)tableView 

sectionForSectionIndexTitle:(NSString *)title 

               atIndex:(NSInteger)index

{

    NSString *key = [keys objectAtIndex:index];

    if (key == UITableViewIndexSearch)

    {

        [tableView setContentOffset:CGPointZero animated:NO];

        return NSNotFound;

    }

    else return index;

    

}

猜你喜欢

转载自blog.csdn.net/ck_19900710/article/details/49738711