1. 程式人生 > >UITableview右側索引以及按名字排序

UITableview右側索引以及按名字排序

UITableview右側索引

右側索引功能是iOS很常見的功能,在通訊錄就得到了完美應用,在說這個功能之前,我們首先了解一個按首字母或者漢字拼音首字母分組排序索引的類。它能夠根據地區來生成與之對應區域索引標題。不需要直接建立它的物件,我們可以通過 UILocalizedIndexedCollation +currentCollation 獲得一個對應當前地區的單例物件。

UILocalizedIndexedCollation

UILocalizedIndexedCollation 的首要任務就是決定對於當前地區區域索引標題應該是什麼,我們可以通過 sectionIndexTitles

 屬性來獲得它們。

下面直接放程式碼:

- (void)setObjects:(NSArray *)objects {
    UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
    
    NSInteger sectionTitlesCount = [[collation sectionTitles] count];
    
   _mutableSections = [NSMutableArray arrayWithCapacity:sectionTitlesCount];
    for (int i = 0; i < sectionTitlesCount; i++) {
        NSMutableArray *subArr = [NSMutableArray array];
        [_mutableSections addObject:subArr];
    }
    
    for (BeanModel *bean in _beanArr) {
        NSInteger section = [collation sectionForObject:bean collationStringSelector:@selector(name)];
        NSMutableArray *subArr = _mutableSections[section];
        
        [subArr addObject:bean];
    }
    
    for (NSMutableArray *subArr in _mutableSections) {
        NSArray *sortArr = [collation sortedArrayFromArray:subArr collationStringSelector:@selector(name)];
        [subArr removeAllObjects];
        [subArr addObjectsFromArray:sortArr];
    }
}

UITableview顯示右側索引

- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section
{
     return [[[UILocalizedIndexedCollation currentCollation] sectionTitles] objectAtIndex:section];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
     return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
}

- (NSInteger)tableView:(UITableView *)tableView
sectionForSectionIndexTitle:(NSString *)title
               atIndex:(NSInteger)index
{
     return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index];
}

修改右側索引樣式以及header title樣式

//修改titleForHeaderInSection title的屬性
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    
    header.contentView.backgroundColor= [UIColor colorWithRed:246/255.0 green:246/255.0 blue:246/255.0 alpha:1];
    
    [header.textLabel setTextColor:[UIColor colorWithHexString:@"4778CC"]];
    
    [header.textLabel setFont:[UIFont systemFontOfSize:15.f]];
}