服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - IOS - iOS tableView实现搜索功能

iOS tableView实现搜索功能

2021-04-06 15:32joker_wlk IOS

这篇文章主要为大家详细介绍了iOS tableView实现搜索功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

github里面有详细的说明

支持中文排序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#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

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

原文链接:http://blog.csdn.net/joker_wlk/article/details/52164628

延伸 · 阅读

精彩推荐
  • IOS关于iOS自适应cell行高的那些事儿

    关于iOS自适应cell行高的那些事儿

    这篇文章主要给大家介绍了关于iOS自适应cell行高的那些事儿,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的...

    daisy6092021-05-17
  • IOS解析iOS开发中的FirstResponder第一响应对象

    解析iOS开发中的FirstResponder第一响应对象

    这篇文章主要介绍了解析iOS开发中的FirstResponder第一响应对象,包括View的FirstResponder的释放问题,需要的朋友可以参考下...

    一片枫叶4662020-12-25
  • IOSiOS 雷达效果实例详解

    iOS 雷达效果实例详解

    这篇文章主要介绍了iOS 雷达效果实例详解的相关资料,需要的朋友可以参考下...

    SimpleWorld11022021-01-28
  • IOSIOS开发之字典转字符串的实例详解

    IOS开发之字典转字符串的实例详解

    这篇文章主要介绍了IOS开发之字典转字符串的实例详解的相关资料,希望通过本文能帮助到大家,让大家掌握这样的方法,需要的朋友可以参考下...

    苦练内功5832021-04-01
  • IOSiOS中tableview 两级cell的展开与收回的示例代码

    iOS中tableview 两级cell的展开与收回的示例代码

    本篇文章主要介绍了iOS中tableview 两级cell的展开与收回的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    J_Kang3862021-04-22
  • IOSiOS布局渲染之UIView方法的调用时机详解

    iOS布局渲染之UIView方法的调用时机详解

    在你刚开始开发 iOS 应用时,最难避免或者是调试的就是和布局相关的问题,下面这篇文章主要给大家介绍了关于iOS布局渲染之UIView方法调用时机的相关资料...

    windtersharp7642021-05-04
  • IOSIOS 屏幕适配方案实现缩放window的示例代码

    IOS 屏幕适配方案实现缩放window的示例代码

    这篇文章主要介绍了IOS 屏幕适配方案实现缩放window的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要...

    xiari5772021-06-01
  • IOSiOS通过逆向理解Block的内存模型

    iOS通过逆向理解Block的内存模型

    自从对 iOS 的逆向初窥门径后,我也经常通过它来分析一些比较大的应用,参考一下这些应用中某些功能的实现。这个探索的过程乐趣多多,不仅能满足自...

    Swiftyper12832021-03-03