简单实现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:https://files.cnblogs.com/files/sixindev/tableviewIndex.zip
作者:SIBU iOS DEV
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步