開篇之前尺栖,我們先來看一下我們即將實(shí)現(xiàn)的效果:
下面通過代碼來了解一下其實(shí)現(xiàn)邏輯
首先嫡纠,創(chuàng)建一個(gè)PersonData的類 ,屬性可以自定義無限制添加,在此只要一個(gè)屬性name除盏。
#import <Foundation/Foundation.h>
@interface PersonData : NSObject
@property(nonatomic,strong)NSString *name;
@end
緊接著就是UITableView和UISearchBar的結(jié)合叉橱,我們創(chuàng)建一個(gè)控制器,并聲明幾個(gè)屬性
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,strong)NSArray *tableData;
@property(nonatomic,strong)NSMutableArray *requltData;
@property(nonatomic,strong)NSArray *tableIndexData;
@property(nonatomic,strong)NSMutableArray *requltIndexData;
@property(nonatomic,assign)BOOL searchActive;
@end
-(void)test{
UISearchBar *searchBar = [[UISearchBar alloc]init];
[searchBar sizeToFit];
searchBar.delegate = self;
[searchBar setAutocorrectionType:UITextAutocorrectionTypeNo];
_tableView.tableHeaderView = searchBar;
_tableView.sectionIndexColor = [UIColor grayColor];
[_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
_tableView.dataSource = self;
_tableView.delegate = self;
NSArray *arr = @[@"張三",@"李四",@"王五",@"劉二",@"石小文",@"范玉",@"梁濤濤",@"杜玉真",@"張宇",@"趙四",@"劉能"];//,@"沈海鵬",@"曾志偉"
NSMutableArray *personArray = [NSMutableArray arrayWithCapacity:arr.count];
for (NSString *name in arr) {
PersonData *data = [[PersonData alloc]init];
data.name = name;
[personArray addObject:data];
}
NSArray *tempArray = [self groupingSortingWithObjects:personArray withSelector:@selector(name) isEmptyArray:YES];
self.tableData = tempArray[0];
self.tableIndexData = tempArray[1];
}
做好了以上的準(zhǔn)備工作者蠕,接下來就開始今天的重點(diǎn),在這里我們需要把本地所有的數(shù)據(jù)模型根據(jù)name屬性進(jìn)行分組來獲取一個(gè)索引數(shù)組窃祝,以及一個(gè)用于顯示UI的數(shù)據(jù)源數(shù)組。集體實(shí)現(xiàn)邏輯如下
/**
將傳進(jìn)來的數(shù)據(jù)模型分組并排序 分成若干個(gè)分組 每個(gè)分組也進(jìn)行排序 并刪除分組中為空的分組
@param objects 初始的對(duì)象數(shù)組
@param selector 屬性名稱
@param empty 清空與否
@return 返回一個(gè)大數(shù)組 數(shù)組中是小數(shù)組 小數(shù)組中存儲(chǔ)模型對(duì)象
*/
-(NSArray *)groupingSortingWithObjects:(NSArray *)objects withSelector:(SEL)selector isEmptyArray:(BOOL)empty{
//UILocalizedIndexedCollation的分組排序建立在對(duì)對(duì)象的操作之上
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
//得到collation索引數(shù)量(26個(gè)字母和1個(gè)#)
NSMutableArray *indexArray = [NSMutableArray arrayWithArray:collation.sectionTitles];
NSUInteger sectionNumber = [indexArray count];//sectionNumber = 27
//建立每個(gè)section數(shù)組
NSMutableArray *sectionArray = [NSMutableArray arrayWithCapacity:sectionNumber];
for (int index = 0; index < sectionNumber; index++) {
NSMutableArray *subArray = [NSMutableArray array];
[sectionArray addObject:subArray];
}
for (PersonData *model in objects) {
//根絕SEL方法返回的字符串判斷對(duì)象應(yīng)該處于哪個(gè)分區(qū)
//將每個(gè)人按name分到某個(gè)section下
NSInteger index = [collation sectionForObject:model collationStringSelector:selector];//獲取name屬性的值所在的位置踱侣,比如“林”首字母是L,則就把林放在L組中
NSMutableArray *tempArray = sectionArray[index];
[tempArray addObject:model];
}
//對(duì)每個(gè)section中的數(shù)組按照name屬性排序
for (NSMutableArray *arr in sectionArray) {
NSArray *sortArr = [collation sortedArrayFromArray:arr collationStringSelector:selector];
[arr removeAllObjects];
[arr addObjectsFromArray:sortArr];
}
//是不是刪除空數(shù)組
if (empty) {
[sectionArray enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSArray *obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.count == 0) {
[sectionArray removeObjectAtIndex:idx];
[indexArray removeObjectAtIndex:idx];
}
}];
}
//第一個(gè)數(shù)組為tableView的數(shù)據(jù)源 第二個(gè)數(shù)組為索引數(shù)組 A B C......
return @[sectionArray,indexArray];
}
我們?cè)谳斎胨阉麝P(guān)鍵詞的時(shí)候需要實(shí)現(xiàn)UISecrchBar的UISecrchBarDelegate中的-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText方法
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if (searchText.length == 0) {
_searchActive = NO;
[self.tableView reloadData];
return;
}
_searchActive = YES;
_requltData = [NSMutableArray array];
_requltIndexData = [NSMutableArray array];
dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
dispatch_async(globalQueue, ^{
[self.tableData enumerateObjectsUsingBlock:^(NSMutableArray *obj, NSUInteger adx, BOOL * _Nonnull stop) {
if (_requltData.count == 0 || [[_requltData lastObject] count] != 0) {
[_requltData addObject:[NSMutableArray array]];
}
[obj enumerateObjectsUsingBlock:^(PersonData *person, NSUInteger bdx, BOOL * _Nonnull stop) {
NSString *tempStr = person.name;
NSString *pinyin = [self transformToPinyin:tempStr isQuanpin:NO];
if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0) {
[_requltData.lastObject addObject:person];
if (_requltIndexData == 0 || ![_requltIndexData.lastObject isEqualToString:_tableIndexData[adx]]) {
[_requltIndexData addObject:_tableIndexData[adx]];
}
}
}];
}];
if ([_requltData.lastObject count] == 0) {
[_requltData removeLastObject];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
-(NSString *)transformToPinyin:(NSString *)originalString isQuanpin:(BOOL)quanpin{
NSMutableString *muStr = [NSMutableString stringWithString:originalString];
//漢字轉(zhuǎn)成拼音
CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformMandarinLatin, NO);
//去掉音標(biāo)
CFStringTransform((CFMutableStringRef)muStr, NULL, kCFStringTransformStripDiacritics, NO);
NSArray *pinyinArray = [muStr componentsSeparatedByString:@" "];
NSMutableString *allString = [NSMutableString new];
if (quanpin) {
int count = 0;
for (int i = 0; i < pinyinArray.count; i++)
{
for (int i = 0; i < pinyinArray.count; i++) {
if (i == count)
{
[allString appendString:@"#"];
}
[allString appendFormat:@"%@",pinyinArray[i]];
}
[allString appendString:@","];
count++;
}
}
NSMutableString *initialStr = [NSMutableString new];
for (NSString *str in pinyinArray) {
if ([str length] > 0) {
[initialStr appendString:[str substringFromIndex:1]];
}
}
[allString appendFormat:@"#%@",initialStr];
[allString appendFormat:@",#%@",originalString];
return allString;
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}
最后實(shí)現(xiàn)
UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return _searchActive ? _requltData.count : _tableData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return _searchActive ? [_requltData[section] count] : [_tableData[section] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
PersonData * m = _searchActive ? _requltData[indexPath.section][indexPath.row] : _tableData[indexPath.section][indexPath.row];
cell.textLabel.text = m.name;
return cell;
}
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return _searchActive ? _requltIndexData : _tableIndexData;
}
-(NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
return [[UILocalizedIndexedCollation currentCollation]sectionForSectionIndexTitleAtIndex:index];
}
#pragma mark - Table View Delegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel * tempLab = [[UILabel alloc] initWithFrame:CGRectMake(30, 0, self.view.bounds.size.width, 20)];
// tempLab.textAlignment = NSTextAlignmentCenter;
tempLab.text = _searchActive ? _requltIndexData[section] : _tableIndexData[section];
tempLab.backgroundColor = [UIColor colorWithRed:243/255.0 green:243/255.0 blue:243/255.0 alpha:1.0];
return tempLab;
}
以上就是左右的邏輯設(shè)計(jì)與實(shí)現(xiàn)過程粪小。 另外有一點(diǎn)大家需要注意一點(diǎn) 有一些多音字的在分組的時(shí)候顯示的并不是那么友好,比如:沈 是多音字抡句,也念ceng 會(huì)被分到C組探膊。曾也是一樣等等。待榔。