iOSテーブルビューで検索機能を実現
本論文の例では、tablewiw検索機能の具体的なコードを共有します。参考にしてください。具体的な内容は以下の通りです。
フレーム:https://github.com/honeycao/HCSortAndSearchDemo
githubに詳しい説明があります。
中国語の並べ替えをサポートします
フレーム:https://github.com/honeycao/HCSortAndSearchDemo
githubに詳しい説明があります。
中国語の並べ替えをサポートします
#import "ChineseToPinyin.h"
#import "HCSortString.h"
#import "WLCCityTVC.h"
#import "WLCProvinceModel.h"
#import "ZYPinYinSearch.h"
#define reusedID @"cityCell"
@interface WLCCityTVC () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
/**
* ,
*/
@property (nonatomic, strong) NSMutableArray* cityArrM;
@property (nonatomic, strong) WLCUser* user;
/**
*
*/
@property (nonatomic, strong) NSMutableArray* letterArrM;
@property (nonatomic, strong) NSMutableArray* wordArr;
/**
*
*/
@property (nonatomic, strong) NSMutableArray* modelArrM;
@property (strong, nonatomic) NSMutableArray* searchDataSource; /**< */
@property (strong, nonatomic) UISearchController* searchController;
@end
@implementation WLCCityTVC
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupUI];
}
#pragma mark - navitionBarBackBarItem
- (BOOL)navigationShouldPopOnBackButton
{
self.searchController.active = NO;
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (WLCUser*)user
{
if (nil == _user) {
_user = [NSKeyedUnarchiver unarchiveObjectWithFile:fileUser];
}
return _user;
}
- (NSMutableArray*)cityArrM
{
if (nil == _cityArrM) {
_cityArrM = [NSMutableArray array];
}
return _cityArrM;
}
- (NSMutableArray*)wordArr
{
if (nil == _wordArr) {
_wordArr = [NSMutableArray array];
}
return _wordArr;
}
- (NSMutableArray*)letterArrM
{
if (nil == _letterArrM) {
_letterArrM = [NSMutableArray array];
}
return _letterArrM;
}
- (UISearchController*)searchController
{
if (!_searchController) {
_searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
_searchController.searchResultsUpdater = self;
_searchController.dimsBackgroundDuringPresentation = NO;
_searchController.hidesNavigationBarDuringPresentation = NO;
_searchController.searchBar.placeholder = @" ";
_searchController.searchBar.tintColor = [UIColor whiteColor];
[_searchController.searchBar sizeToFit];
}
return _searchController;
}
- (NSMutableArray*)modelArrM
{
if (nil == _modelArrM) {
_modelArrM = [NSMutableArray array];
for (NSArray* tempArr in self.cityArrM) {
for (NSDictionary* dict in tempArr) {
[WLCProvinceModel setupReplacedKeyFromPropertyName:^NSDictionary* {
return @{
@"pID" : @"id"
};
}];
WLCProvinceModel* model = [WLCProvinceModel objectWithKeyValues:dict];
[_modelArrM addObject:model];
}
}
}
return _modelArrM;
}
- (NSMutableArray*)searchDataSource
{
if (nil == _searchDataSource) {
_searchDataSource = [NSMutableArray array];
}
return _searchDataSource;
}
- (void)setupUI
{
self.tableView.backgroundColor = [UIColor rgb:234 andGreen:234 andBlue:243];
[self getAllCities];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.tableFooterView = [[UIView alloc] init];
}
- (void)getAllCities
{
NSString* url = [kURL stringByAppendingString:@"promary/"];
url = [url stringByAppendingString:self.cityID];
url = [url stringByAppendingString:@"/city"];
[SVProgressHUD showWithStatus:@" "];
[NetRequestTool requestWithParamsDict:nil image:nil name:nil token:self.user.token value:nil hearerField:nil URL:url type:GET successBlock:^(AFHTTPRequestOperation* _Nonnull operation, id _Nonnull responseObject) {
NSString* errNum = [NSString stringWithFormat:@"%@", responseObject[@"errNum"]];
if ([errNum isEqualToString:@"1"]) {
[SVProgressHUD setMinimumDismissTimeInterval:2.5];
[SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@", responseObject[@"retMsg"]]];
[self.navigationController popViewControllerAnimated:YES];
}
else {
[SVProgressHUD dismiss];
@try {
self.cityArrM = responseObject[@"retData"];
NSMutableArray* cityArrM = [NSMutableArray array];
for (NSMutableDictionary* cityDic in self.cityArrM) {
[cityArrM addObject:[cityDic objectForKey:@"name"]];
NSMutableDictionary* dictM = [NSMutableDictionary dictionaryWithDictionary:cityDic];
[self prepareCityListDatasourceWithArray:cityArrM andToDictionary:dictM];
}
self.cityArrM = [self sortArray:self.wordArr];
} @catch (NSException* exception) {
} @finally {
[self.tableView setTableHeaderView:self.searchController.searchBar];
[self.tableView reloadData];
}
}
}
anderrorBlock:^(AFHTTPRequestOperation* _Nonnull operation, NSError* _Nonnull error) {
WLog(@"error == %@", error);
[SVProgressHUD showErrorWithStatus:@" , "];
[self.navigationController popViewControllerAnimated:YES];
}];
}
#pragma mark -
- (void)prepareCityListDatasourceWithArray:(NSArray*)array andToDictionary:(NSMutableDictionary*)dic
{
for (NSString* city in array) {
NSString* cityPinyin = [ChineseToPinyin pinyinFromChiniseString:city];
if ([city isEqualToString:@" "]) {
cityPinyin = @"CHONGQING";
}
NSString* firstLetter = [cityPinyin substringWithRange:NSMakeRange(0, 1)];
if (![dic objectForKey:firstLetter]) {
// NSMutableArray* arr = [NSMutableArray array];
// [dic setValue:firstLetter forKey:@"letter"];
dic[@"letter"] = firstLetter;
}
if ([[dic objectForKey:firstLetter] containsObject:city]) {
return;
}
}
[self.wordArr addObject:dic];
// [self.wordArr addObjectsFromArray:[[dic allValues] sortedArrayUsingSelector:@selector(compare:)]];
}
/**
*
*
* @param arrayToSort <#arrayToSort description#>
*
* @return <#return value description#>
*/
- (NSMutableArray*)sortArray:(NSMutableArray*)arrayToSort
{
NSMutableArray* arrayForArrays = [[NSMutableArray alloc] init];
//
NSArray* sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"letter" ascending:YES]];
//
[arrayToSort sortUsingDescriptors:sortDescriptors];
NSMutableArray* tempArray = nil;
BOOL flag = NO;
//
for (int i = 0; i < arrayToSort.count; i++) {
NSString* pinyin = [arrayToSort[i] objectForKey:@"letter"];
NSString* firstChar = [pinyin substringToIndex:1];
// NSLog(@"%@",firstChar);
if (![self.letterArrM containsObject:[firstChar uppercaseString]]) {
[self.letterArrM addObject:[firstChar uppercaseString]];
tempArray = [[NSMutableArray alloc] init];
flag = NO;
}
if ([self.letterArrM containsObject:[firstChar uppercaseString]]) {
[tempArray addObject:arrayToSort[i]];
if (flag == NO) {
[arrayForArrays addObject:tempArray];
flag = YES;
}
}
}
return arrayForArrays;
}
// cell
- (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
}
if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
[cell setPreservesSuperviewLayoutMargins:NO];
}
if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
#pragma mark - tableView's delegate and datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
if (!self.searchController.active) {
return self.letterArrM.count;
}
else {
return 1;
}
}
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
if (!self.searchController.active) {
return [self.cityArrM[section] count];
}
else {
return self.searchDataSource.count;
}
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reusedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedID];
}
@try {
if (!self.searchController.active) {
NSDictionary* dict = self.cityArrM[indexPath.section][indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@", dict[@"name"]];
}
else {
// NSDictionary* dict = self.searchDataSource[indexPath.row];
WLCProvinceModel* model = self.searchDataSource[indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@", model.name];
}
} @catch (NSException* exception) {
} @finally {
}
return cell;
}
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
if (!self.searchController.active) {
return [self.letterArrM objectAtIndex:section];
}
else
return nil;
}
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
if (!self.searchController.active) {
return self.letterArrM;
}
else
return nil;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
NSDictionary* dict;
@try {
if (!self.searchController.active) {
dict = self.cityArrM[indexPath.section][indexPath.row];
}
else {
WLCProvinceModel* model = self.searchDataSource[indexPath.row];
dict = [NSDictionary dictionaryWithObjects:@[ model.name, model.pID ] forKeys:@[ @"name", @"id" ]];
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"cityChoosed" object:self userInfo:dict];
} @catch (NSException* exception) {
} @finally {
}
self.searchController.active = NO;
[self.navigationController popToViewController:self.fatherVC animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UISearchDelegate
- (void)updateSearchResultsForSearchController:(UISearchController*)searchController
{
[self.searchDataSource removeAllObjects];
NSArray* ary = [NSArray new];
//
NSDictionary* allDataSource = [HCSortString sortAndGroupForArray:self.modelArrM PropertyName:@"name"];
ary = [HCSortString getAllValuesFromDict:allDataSource];
if (searchController.searchBar.text.length == 0) {
[self.searchDataSource addObjectsFromArray:ary];
}
else {
ary = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchController.searchBar.text andSearchByPropertyName:@"name"];
[self.searchDataSource addObjectsFromArray:ary];
}
[self.tableView reloadData];
}
@end
以上が本文の全部です。皆さんの勉強に役に立つように、私たちを応援してください。