iOS拼音搜索,拼音首字母搜索

扩展了一下 搜索框,能够实现拼音和首字母模糊搜索
基本搜索 上一篇文章

#import "NSString+utility.h"

@interface WJWPinyinSearchViewController ()<UISearchResultsUpdating,UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate>

@property (nonatomic, strong) UITableViewController *searchTableViewController;
@property (nonatomic, strong) UISearchController *searchController;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *searchList;

@end

@implementation WJWPinyinSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addChildViewController:self.searchTableViewController];
    [self initDataArray];
    [self configUI];
}

- (void)initDataArray{
    [self.dataArray addObject:@"世界"];
    [self.dataArray addObject:@"核平"];
    [self.dataArray addObject:@"平行"];
    [self.dataArray addObject:@"宇宙"];
    [self.dataArray addObject:@"技术进步"];
    [self.dataArray addObject:@"毫无意义"];
    [self.dataArray addObject:@"尘归尘,土归土"];
    [self.dataArray addObject:@"中"];
    [self.dataArray addObject:@"国"];
    [self.dataArray addObject:@"红"];

}

- (void)configUI {
    
    [self.view addSubview: self.searchTableViewController.tableView];
    self.searchTableViewController.tableView.frame = self.view.frame;
}

#pragma mark ---UITableViewDataSource---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active) {
        return [self.searchList count];
    }else {
        return self.dataArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *searchCellId = @"SearchCellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:searchCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:searchCellId];
    }
    if (self.searchController.active) {
        [cell.textLabel setText:self.searchList[indexPath.row]];
    }else {
        [cell.textLabel setText:self.dataArray[indexPath.row]];
    }
    return cell;
}


#pragma mark ----UISearchResultsUpdating----

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = [self.searchController.searchBar text];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
    if (self.searchList != nil) {
        [self.searchList removeAllObjects];
    }
    //过滤数据
    self.searchList = [NSMutableArray arrayWithArray:[_dataArray filteredArrayUsingPredicate:predicate]];
    //刷新表格
    [self.searchTableViewController.tableView reloadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"输入字符串为:%@ -- %lu", searchText, (unsigned long)searchText.length);
    //需要事先清空存放搜索结果的数组
    [self.searchList removeAllObjects];
    
    //在子线程中做搜索操作
    dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);
    dispatch_async(globalQueue, ^{
        if (searchText != nil && searchText.length > 0) {
            for (NSString *tempStr in self.dataArray) {
                NSString *pinyin = [tempStr transformToPinyin:tempStr];
                NSLog(@"字符拼音:%@",pinyin);
                if ([pinyin rangeOfString:searchText options:NSCaseInsensitiveSearch].length > 0) {
                    [self.searchList addObject:tempStr];
                }
            }
        }else {
            self.searchList = [NSMutableArray arrayWithArray:self.dataArray];
        }
        //回到主线程刷新表格
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.searchTableViewController.tableView reloadData];
        });
    });
}


-(UISearchController *)searchController {
    if (!_searchController) {
        _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = self;
        _searchController.dimsBackgroundDuringPresentation = NO;
        _searchController.hidesNavigationBarDuringPresentation = YES;//搜索框编辑时隐藏导航栏
        _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, _searchController.searchBar.frame.origin.y, _searchController.searchBar.frame.size.width, 44.0);
        self.searchTableViewController.tableView.tableHeaderView = _searchController.searchBar;
        _searchController.searchBar.delegate = self;
    }
    return _searchController;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (UITableViewController *)searchTableViewController {
    if (!_searchTableViewController) {
        _searchTableViewController = [[UITableViewController alloc] init];
        _searchTableViewController.tableView.delegate = self;
        _searchTableViewController.tableView.dataSource = self;
    }
    return _searchTableViewController;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

"NSString+utility.h" 中有一个方法用来将字符转为拼音字符串

/**
 把汉字字符串转为拼音

 @param aString 汉字字符串
 @return 拼音字符串
 */
- (NSString *)transformToPinyin:(NSString *)aString
{
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    NSArray *pinyinArray = [str componentsSeparatedByString:@" "];
    NSMutableString *allString = [NSMutableString new];
    
    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 *s in pinyinArray)
    {
        if (s.length > 0)
        {
            [initialStr appendString:  [s substringToIndex:1]];
        }
    }
    [allString appendFormat:@"#%@",initialStr];
    [allString appendFormat:@",#%@",aString];
    return allString;
}
posted @ 2019-04-18 00:21  wjwdive  阅读(1283)  评论(0编辑  收藏  举报