ios开发:搜索、索引

一、搜索框

@property (nonatomic, strong) UISearchBar    *searchBar;
//搜索控制器
@property (nonatomic, strong) UISearchDisplayController *sdc;
//<5>UISearchBar
//搜索框的大小:全屏的宽*44
//把搜索框放到tableView上面
_tableView.tableHeaderView = _searchBar;
 //<6>UISearchDisplayController搜索控制器
    //搜索控制器在实例化时会将搜索框与本个控制器关联起来
    _sdc = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
    //UISearchDisplayController本身就存在一个UITableView,这个UITableView也是需要遵守协议和代理,这个tableView只有一段,如果执行这个代理方法的tableView不是我们自己手动创建的,那么他就是UISearchDisplayController管理的那一个tableView并且每个UITableView的代理方法都要判断是不是手动创建的那个if (tableView != _tableView)

//UISearchDisplayController管理的UITableView的协议代理
    _sdc.searchResultsDataSource = self;
    _sdc.searchResultsDelegate = self;
//UISearchDisplayController本身又有一个delegate,需要遵守本身的代理方法UISearchDisplayDelegate
    _sdc.delegate = self;
if (tableView != _tableView) {
        cell.textLabel.text = _resultArray[indexPath.row];
    }else{
        cell.textLabel.text = _dataArray[indexPath.section][indexPath.row];
#pragma mark - UISearchDisplayDelegate
//当输入框里面的文字出现改变就执行
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
    //清空之前的搜索结果
    [_resultArray removeAllObjects];
    //searchString  输入框里面的文字
    for (NSArray *arr in _dataArray) {
        for (NSString *str in arr) {
            //查找
            NSRange range = [str rangeOfString:searchString];
            if (range.length != 0) {
                [_resultArray addObject:str];
            }
        }
    }
    return YES;
}

二、索引

 //设置索引文字颜色:默认蓝色
    _tableView.sectionIndexColor = [UIColor redColor];
    //设置索引背景条的颜色:默认透明
    _tableView.sectionIndexBackgroundColor = [UIColor grayColor];
    //设置点击索引时背景条的颜色:默认透明
    _tableView.sectionIndexTrackingBackgroundColor = [UIColor cyanColor];
#pragma mark - 索引相关方法
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:0];
    //搜索小图标
    [array addObject:UITableViewIndexSearch];
    for (int i = 'a'; i <= 'z'; i ++) {
        [array addObject:[NSString stringWithFormat:@"%c",i]];
    }
    return array;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    //index  索引的下标
    //index  能对应到tableView的段
    if (index == 0) {
        NSLog(@"search");
    }
    return index - 1;  
}

你可能感兴趣的:(ios开发:搜索、索引)