简单实现UITableView索引功能(中英文首字母索引) (二) By HL

简单实现UITableView索引功能(中英文首字母索引)(一) ByH罗

相关类:

NSString+PinYing(获取中英文首字母)   参考上面链接

#import "ViewController.h"
#import "contactModel.h"
#import "NSArray+ContactArray.h"
#define kScreen_Height   ([UIScreen mainScreen].bounds.size.height)
#define kScreen_Width    ([UIScreen mainScreen].bounds.size.width)

 

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UISearchDisplayDelegate>

@property(nonatomic,strong)  UITableView *tableView;
@property(nonatomic,strong)  NSMutableArray     *dataArray;
@property(nonatomic,strong)  NSArray     *indexArray;

@property(nonatomic,strong) UISearchBar  *searchBar;
@property(nonatomic,strong) UISearchDisplayController  *mSearchDisplayController;
@property(nonatomic,strong) NSMutableArray    *filteredPersons;         //搜索过滤后  搜索结果

@end
@implementation ViewControlle

 

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.title=@"索引";

    NSArray *array=@[
                 @{@"contact":@"lulu",
                  @"conatctUrl":@"147456140992" },
                  @{ @"contact":@"哈尼",
                    @"conatctUrl":@"189234342"},
                 @{ @"contact":@"陆军",
                    @"conatctUrl":@"15475654785"},
                 @{ @"contact":@"是的",
                    @"conatctUrl":@"1873895343"},
                 @{ @"contact":@"身份",
                    @"conatctUrl":@"15688382345"},
                 @{ @"contact":@"爱德华",
                    @"conatctUrl":@"14754565443"},
                 ];
    _filteredPersons = [NSMutableArray array];
    _dataArray=[NSMutableArray array];
    for (NSDictionary *dict in array) {
        contactModel  *model = [[contactModel alloc] init];
        model.contactName=dict[@"contact"];
        model.contactUrl=dict[@"conatctUrl"];
        [_dataArray addObject:model];
    }
    
    //索引
   self.indexArray=[self.dataArray arrayWithPinYinFirstLetter];
    
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView=self.searchBar;
    self.tableView.tableFooterView=[[UIView alloc]init];
    self.tableView.keyboardDismissMode=UIScrollViewKeyboardDismissModeOnDrag;
    
    self.mSearchDisplayController.searchResultsTableView.tableFooterView=[[UIView alloc]init];//隐藏多余分割线
}



-(UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] init];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索";
        [_searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [_searchBar sizeToFit];
        _searchBar.barTintColor=[UIColor redColor];
        [[UIBarButtonItem appearanceWhenContainedIn:[UISearchBar class], nil] setTitle:@"取消"];
    }
    return _searchBar;
}

-(UISearchDisplayController *)mSearchDisplayController
{
    if (!_mSearchDisplayController) {
        _mSearchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
        _mSearchDisplayController.searchResultsDelegate = self;
        _mSearchDisplayController.searchResultsDataSource = self;
        _mSearchDisplayController.delegate = self;
    }
    return _mSearchDisplayController;
}



#pragma mark----CreatMyCustomTablevIew-----
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView  alloc] initWithFrame:CGRectMake(0,0,kScreen_Width, kScreen_Height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"REUSE_CELLID"];
        _tableView.contentSize=CGSizeMake(kScreen_Width,kScreen_Height*2);
        _tableView.sectionIndexBackgroundColor=[UIColor clearColor];//索引背景色
        _tableView.sectionIndexColor=[UIColor redColor];//索引背景色
    }
    return _tableView;
}

 

 

//在tableview中有多少个分组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView==self.tableView) {
        return self.indexArray.count;
    }
    return 1;
}



#pragma mark--- UITableViewDataSource and UITableViewDelegate Methods---
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.mSearchDisplayController.searchResultsTableView)
    {
        //否则显示搜索出来的数据
        return [self.filteredPersons count];
    }
    NSDictionary *dict = self.indexArray[section];
    return [dict[@"content"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                     reuseIdentifier:CellIdentifier];
    }
    contactModel *model;
    if (tableView == self.mSearchDisplayController.searchResultsTableView)
    {
        model = [self.filteredPersons objectAtIndex:indexPath.row];
    }else{
        NSDictionary *dict = self.indexArray[indexPath.section];
        model=dict[@"content"][indexPath.row];
    }
    cell.textLabel.text=model.contactName;
    cell.detailTextLabel.text=model.contactUrl;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}


#pragma ---索引
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView==self.tableView) {
        NSDictionary *dict = self.indexArray[section];
        NSString *title =[NSString stringWithFormat:@"  %@",dict[@"firstLetter"]];
        return title;
    }
    return nil;
}

//设置表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    if (tableView==self.tableView) {
        NSMutableArray *resultArray =[NSMutableArray arrayWithObject:UITableViewIndexSearch];
        for (NSDictionary *dict in self.indexArray) {
            NSString *title = dict[@"firstLetter"];
            [resultArray addObject:title];
        }
        return resultArray;
    }
    return 0;
}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    if ([title isEqualToString:UITableViewIndexSearch])
    {
        [tableView setContentOffset:CGPointZero animated:NO];//tabview移至顶部
        return NSNotFound;
    }
    else
    {
        return [[UILocalizedIndexedCollation currentCollation] sectionForSectionIndexTitleAtIndex:index]; // -1 because we add the search symbol
    }
}

 

#pragma --搜索
#pragma mark - UISearchDisplayDelegate
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString

{
    //一旦SearchBar输入內容有变化,则执行这个方法,请问要不要重裝searchResultTableView的数据
    [self filterContentForSearchText:searchString
                               scope:[self.searchBar scopeButtonTitles][self.searchBar.selectedScopeButtonIndex]];
    
    return YES;
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    //如果设置了选项,当Scope Button选项有变化的时候,则执行这个方法,请问要不要重裝searchResultTableView的数据
    [self filterContentForSearchText:self.searchBar.text
                               scope:self.searchBar.scopeButtonTitles[searchOption]];
    return YES;
}

//源字符串内容是否包含或等于要搜索的字符串内容
-(void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
    if ([searchText length]==0) {
        return;
    }
    NSString * regex        = @"(^[0-9]+$)";
    NSPredicate * pred      = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isNum=[pred evaluateWithObject:searchText];//判断是否是数字
    NSMutableArray *tempResults = [NSMutableArray array];
    NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
    for (int i = 0; i < self.dataArray.count; i++) {
        contactModel *model=self.dataArray[i];
        NSString *storeString;
        if (isNum) {
            storeString =model.contactUrl;
        }else{
            storeString =model.contactName;
        }
        /*匹配的规则是:源字符串内容是否包含或等于要搜索的字符串内容*/
        NSRange storeRange = NSMakeRange(0, storeString.length);
        NSRange foundRange = [storeString rangeOfString:searchText options:searchOptions range:storeRange];
        if (foundRange.length) {
            [tempResults addObject:model];
        }
        //把一个数组的值赋给 self.filteredPersons
        [self.filteredPersons removeAllObjects];
        [self.filteredPersons addObjectsFromArray:tempResults];
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"indexPath===%ld",indexPath.row);
    contactModel *model;
   if (tableView==self.mSearchDisplayController.searchResultsTableView){
       model =self.filteredPersons[indexPath.row];
   }else{
       NSDictionary *dict = self.indexArray[indexPath.section-1];
       NSArray  *modeArr=dict[@"content"];
       model = modeArr[indexPath.row];
   }
}

 

 

Demo:http://files.cnblogs.com/files/sixindev/tableviewIndex.zip

 

转载于:https://www.cnblogs.com/sixindev/p/4755174.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值