查看: 610|回复: 0

[IOS开发教程] iOS tableView实现搜索功能

发表于 2017-12-27 08:00:00

本文实例为大家分享了tableView搜索功能的具体代码,供大家参考,具体内容如下

框架:https://github.com/honeycao/HCSortAndSearchDemo

github里面有详细的说明

支持中文排序

  1. #import "ChineseToPinyin.h"
  2. #import "HCSortString.h"
  3. #import "WLCCityTVC.h"
  4. #import "WLCProvinceModel.h"
  5. #import "ZYPinYinSearch.h"
  6. #define reusedID @"cityCell"
  7. @interface WLCCityTVC () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating>
  8. /**
  9. * 存放城市字典的数组,后来也存放排序后的
  10. */
  11. @property (nonatomic, strong) NSMutableArray* cityArrM;
  12. @property (nonatomic, strong) WLCUser* user;
  13. /**
  14. * 存放首字母的数组
  15. */
  16. @property (nonatomic, strong) NSMutableArray* letterArrM;
  17. @property (nonatomic, strong) NSMutableArray* wordArr;
  18. /**
  19. * 存放城市模型的数组
  20. */
  21. @property (nonatomic, strong) NSMutableArray* modelArrM;
  22. @property (strong, nonatomic) NSMutableArray* searchDataSource; /**<搜索结果数据源*/
  23. @property (strong, nonatomic) UISearchController* searchController;
  24. @end
  25. @implementation WLCCityTVC
  26. - (void)viewDidLoad
  27. {
  28. [super viewDidLoad];
  29. [self setupUI];
  30. }
  31. #pragma mark - navitionBarBackBarItem返回事件
  32. - (BOOL)navigationShouldPopOnBackButton
  33. {
  34. self.searchController.active = NO;
  35. return YES;
  36. }
  37. - (void)didReceiveMemoryWarning
  38. {
  39. [super didReceiveMemoryWarning];
  40. // Dispose of any resources that can be recreated.
  41. }
  42. - (WLCUser*)user
  43. {
  44. if (nil == _user) {
  45. _user = [NSKeyedUnarchiver unarchiveObjectWithFile:fileUser];
  46. }
  47. return _user;
  48. }
  49. - (NSMutableArray*)cityArrM
  50. {
  51. if (nil == _cityArrM) {
  52. _cityArrM = [NSMutableArray array];
  53. }
  54. return _cityArrM;
  55. }
  56. - (NSMutableArray*)wordArr
  57. {
  58. if (nil == _wordArr) {
  59. _wordArr = [NSMutableArray array];
  60. }
  61. return _wordArr;
  62. }
  63. - (NSMutableArray*)letterArrM
  64. {
  65. if (nil == _letterArrM) {
  66. _letterArrM = [NSMutableArray array];
  67. }
  68. return _letterArrM;
  69. }
  70. - (UISearchController*)searchController
  71. {
  72. if (!_searchController) {
  73. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  74. _searchController.searchResultsUpdater = self;
  75. _searchController.dimsBackgroundDuringPresentation = NO;
  76. _searchController.hidesNavigationBarDuringPresentation = NO;
  77. _searchController.searchBar.placeholder = @"搜索";
  78. _searchController.searchBar.tintColor = [UIColor whiteColor];
  79. [_searchController.searchBar sizeToFit];
  80. }
  81. return _searchController;
  82. }
  83. - (NSMutableArray*)modelArrM
  84. {
  85. if (nil == _modelArrM) {
  86. _modelArrM = [NSMutableArray array];
  87. for (NSArray* tempArr in self.cityArrM) {
  88. for (NSDictionary* dict in tempArr) {
  89. [WLCProvinceModel setupReplacedKeyFromPropertyName:^NSDictionary* {
  90. return @{
  91. @"pID" : @"id"
  92. };
  93. }];
  94. WLCProvinceModel* model = [WLCProvinceModel objectWithKeyValues:dict];
  95. [_modelArrM addObject:model];
  96. }
  97. }
  98. }
  99. return _modelArrM;
  100. }
  101. - (NSMutableArray*)searchDataSource
  102. {
  103. if (nil == _searchDataSource) {
  104. _searchDataSource = [NSMutableArray array];
  105. }
  106. return _searchDataSource;
  107. }
  108. - (void)setupUI
  109. {
  110. self.tableView.backgroundColor = [UIColor rgb:234 andGreen:234 andBlue:243];
  111. [self getAllCities];
  112. self.tableView.delegate = self;
  113. self.tableView.dataSource = self;
  114. self.tableView.tableFooterView = [[UIView alloc] init];
  115. }
  116. - (void)getAllCities
  117. {
  118. NSString* url = [kURL stringByAppendingString:@"promary/"];
  119. url = [url stringByAppendingString:self.cityID];
  120. url = [url stringByAppendingString:@"/city"];
  121. [SVProgressHUD showWithStatus:@"获取城市中"];
  122. [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) {
  123. NSString* errNum = [NSString stringWithFormat:@"%@", responseObject[@"errNum"]];
  124. if ([errNum isEqualToString:@"1"]) {
  125. [SVProgressHUD setMinimumDismissTimeInterval:2.5];
  126. [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@", responseObject[@"retMsg"]]];
  127. [self.navigationController popViewControllerAnimated:YES];
  128. }
  129. else {
  130. [SVProgressHUD dismiss];
  131. @try {
  132. self.cityArrM = responseObject[@"retData"];
  133. NSMutableArray* cityArrM = [NSMutableArray array];
  134. for (NSMutableDictionary* cityDic in self.cityArrM) {
  135. [cityArrM addObject:[cityDic objectForKey:@"name"]];
  136. NSMutableDictionary* dictM = [NSMutableDictionary dictionaryWithDictionary:cityDic];
  137. [self prepareCityListDatasourceWithArray:cityArrM andToDictionary:dictM];
  138. }
  139. self.cityArrM = [self sortArray:self.wordArr];
  140. } @catch (NSException* exception) {
  141. } @finally {
  142. [self.tableView setTableHeaderView:self.searchController.searchBar];
  143. [self.tableView reloadData];
  144. }
  145. }
  146. }
  147. anderrorBlock:^(AFHTTPRequestOperation* _Nonnull operation, NSError* _Nonnull error) {
  148. WLog(@"error == %@", error);
  149. [SVProgressHUD showErrorWithStatus:@"获取省份失败,请稍后重试"];
  150. [self.navigationController popViewControllerAnimated:YES];
  151. }];
  152. }
  153. #pragma mark -排序城市
  154. - (void)prepareCityListDatasourceWithArray:(NSArray*)array andToDictionary:(NSMutableDictionary*)dic
  155. {
  156. for (NSString* city in array) {
  157. NSString* cityPinyin = [ChineseToPinyin pinyinFromChiniseString:city];
  158. if ([city isEqualToString:@"重庆"]) {
  159. cityPinyin = @"CHONGQING";
  160. }
  161. NSString* firstLetter = [cityPinyin substringWithRange:NSMakeRange(0, 1)];
  162. if (![dic objectForKey:firstLetter]) {
  163. // NSMutableArray* arr = [NSMutableArray array];
  164. // [dic setValue:firstLetter forKey:@"letter"];
  165. dic[@"letter"] = firstLetter;
  166. }
  167. if ([[dic objectForKey:firstLetter] containsObject:city]) {
  168. return;
  169. }
  170. }
  171. [self.wordArr addObject:dic];
  172. // [self.wordArr addObjectsFromArray:[[dic allValues] sortedArrayUsingSelector:@selector(compare:)]];
  173. }
  174. /**
  175. * 排序并按首字母分组
  176. *
  177. * @param arrayToSort <#arrayToSort description#>
  178. *
  179. * @return <#return value description#>
  180. */
  181. - (NSMutableArray*)sortArray:(NSMutableArray*)arrayToSort
  182. {
  183. NSMutableArray* arrayForArrays = [[NSMutableArray alloc] init];
  184. //根据拼音对数组排序
  185. NSArray* sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"letter" ascending:YES]];
  186. //排序
  187. [arrayToSort sortUsingDescriptors:sortDescriptors];
  188. NSMutableArray* tempArray = nil;
  189. BOOL flag = NO;
  190. //分组
  191. for (int i = 0; i < arrayToSort.count; i++) {
  192. NSString* pinyin = [arrayToSort[i] objectForKey:@"letter"];
  193. NSString* firstChar = [pinyin substringToIndex:1];
  194. // NSLog(@"%@",firstChar);
  195. if (![self.letterArrM containsObject:[firstChar uppercaseString]]) {
  196. [self.letterArrM addObject:[firstChar uppercaseString]];
  197. tempArray = [[NSMutableArray alloc] init];
  198. flag = NO;
  199. }
  200. if ([self.letterArrM containsObject:[firstChar uppercaseString]]) {
  201. [tempArray addObject:arrayToSort[i]];
  202. if (flag == NO) {
  203. [arrayForArrays addObject:tempArray];
  204. flag = YES;
  205. }
  206. }
  207. }
  208. return arrayForArrays;
  209. }
  210. //让cell下划线左对齐
  211. - (void)tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath
  212. {
  213. if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
  214. [cell setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
  215. }
  216. if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
  217. [cell setPreservesSuperviewLayoutMargins:NO];
  218. }
  219. if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
  220. [cell setLayoutMargins:UIEdgeInsetsZero];
  221. }
  222. }
  223. #pragma mark - tableView's delegate and datasource
  224. - (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
  225. {
  226. if (!self.searchController.active) {
  227. return self.letterArrM.count;
  228. }
  229. else {
  230. return 1;
  231. }
  232. }
  233. - (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
  234. {
  235. if (!self.searchController.active) {
  236. return [self.cityArrM[section] count];
  237. }
  238. else {
  239. return self.searchDataSource.count;
  240. }
  241. }
  242. - (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
  243. {
  244. UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reusedID];
  245. if (!cell) {
  246. cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedID];
  247. }
  248. @try {
  249. if (!self.searchController.active) {
  250. NSDictionary* dict = self.cityArrM[indexPath.section][indexPath.row];
  251. cell.textLabel.text = [NSString stringWithFormat:@"%@", dict[@"name"]];
  252. }
  253. else {
  254. // NSDictionary* dict = self.searchDataSource[indexPath.row];
  255. WLCProvinceModel* model = self.searchDataSource[indexPath.row];
  256. cell.textLabel.text = [NSString stringWithFormat:@"%@", model.name];
  257. }
  258. } @catch (NSException* exception) {
  259. } @finally {
  260. }
  261. return cell;
  262. }
  263. - (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
  264. {
  265. if (!self.searchController.active) {
  266. return [self.letterArrM objectAtIndex:section];
  267. }
  268. else
  269. return nil;
  270. }
  271. - (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
  272. {
  273. if (!self.searchController.active) {
  274. return self.letterArrM;
  275. }
  276. else
  277. return nil;
  278. }
  279. - (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
  280. {
  281. NSDictionary* dict;
  282. @try {
  283. if (!self.searchController.active) {
  284. dict = self.cityArrM[indexPath.section][indexPath.row];
  285. }
  286. else {
  287. WLCProvinceModel* model = self.searchDataSource[indexPath.row];
  288. dict = [NSDictionary dictionaryWithObjects:@[ model.name, model.pID ] forKeys:@[ @"name", @"id" ]];
  289. }
  290. [[NSNotificationCenter defaultCenter] postNotificationName:@"cityChoosed" object:self userInfo:dict];
  291. } @catch (NSException* exception) {
  292. } @finally {
  293. }
  294. self.searchController.active = NO;
  295. [self.navigationController popToViewController:self.fatherVC animated:YES];
  296. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  297. }
  298. #pragma mark - UISearchDelegate
  299. - (void)updateSearchResultsForSearchController:(UISearchController*)searchController
  300. {
  301. [self.searchDataSource removeAllObjects];
  302. NSArray* ary = [NSArray new];
  303. //对排序好的数据进行搜索
  304. NSDictionary* allDataSource = [HCSortString sortAndGroupForArray:self.modelArrM PropertyName:@"name"];
  305. ary = [HCSortString getAllValuesFromDict:allDataSource];
  306. if (searchController.searchBar.text.length == 0) {
  307. [self.searchDataSource addObjectsFromArray:ary];
  308. }
  309. else {
  310. ary = [ZYPinYinSearch searchWithOriginalArray:ary andSearchText:searchController.searchBar.text andSearchByPropertyName:@"name"];
  311. [self.searchDataSource addObjectsFromArray:ary];
  312. }
  313. [self.tableView reloadData];
  314. }
  315. @end
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。



回复

使用道具 举报