The effect of the search box shows:
This is the so-called search box, so let's take a look at how to use the code to implement this feature.
The data I use is the Hero League hero List, which is a TXT file for JSON data, and the processing code for the JSON data is as follows:
?
123456 |
//获取文件的路径path NSString *path = [[NSBundle mainBundle] pathForResource:@"heros" ofType:@"txt"]; //将路径下的文件转换成NSData数据 NSData *data = [NSData dataWithContentsOfFile:path]; //将得到的NSdata数据进行JSON解析并返回一个结果数组result id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; |
Let's look at the hierarchical relationship of data:
This is explained here that the hierarchical relationship is obtained through the online Code format page, and the data processing we have done in the previous step is to process the raw data and get an array of results, which is the same as the hierarchical relationship and formatting, so that the data can be further processed according to the hierarchical relationship on the formatted page. Put what you need into an array or dictionary (or, of course, print result to see the hierarchy and personal habits).
So what we need is the value of nick in the dictionary, which we iterate through to put into the array, which defines the array as a property, which is used in other methods.
?
1234 |
// 将搜索范围的内容放入数组 for (NSDictionary *diction in result) { [self.arrOfSeachBoxes addObject:diction[@ "nick" ]]; } |
Next we create a uitableview used to display the data, the search bar needs to use the class is UISearchController
, first see how to create:
The system's comments are clear, if you want to display the search results on the current page, the parameters of this method can be nil, for the sake of convenience, declare a UISearchController
property
?
1 |
@property (nonatomic, retain) UISearchController *searchController; |
The next step is to create
?
12 |
// nil表示在当前页面显示搜索结果 self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil]; |
A property that is placed in a very forward position in the Uisearchcontroller header file
We can guess by the literal meaning that this is related to the update of the search results tableView
reloadData
. So obviously, we have to sign the agreement < UISearchResultsUpdating
, there is only one method that must be implemented in this agreement.
?
1 |
- ( void )updateSearchResultsForSearchController:(UISearchController *)searchController; |
The header file looks like this:
---------here is the beautiful dividing line---------
All the classes and methods of the search bar have been listed above, and the following is a smooth
All the defined properties are as follows:
?
12345678 |
NS_ASSUME_NONNULL_BEGIN @interface ViewController () <UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating> @property (nonatomic, retain) NSMutableArray *arrOfSeachBoxes; /**< 搜索范围 */ @property (nonatomic, retain) NSMutableArray *arrOfSeachResults; /**< 搜索结果 */ @property (nonatomic, retain) UISearchController *searchController; @property (nonatomic, retain) UITableView *tableView; @end NS_ASSUME_NONNULL_END |
The data processing related code is as follows:
?
123456789 |
//parse data nsstring *path = [[NSBundle] Mainbundle] pathforresource:@ "heros" oftype:@ "txt" ]; nsdata *data = [NSData Datawithcontentsoffile:path]; id result = [nsjsonserialization jsonobjectwithdata:data options: Nsjsonreadingmutablecontainers Error:nil]; self.arrofseachboxes = [Nsmutablearray array]; //the contents of the search scope into the array for (nsdictionary *dic in result) { &NBSP; [self.arrofseachboxes addobject:dic[@ } |
The associated code for creating the Uisearchcontroller is as follows:
?
1234567891011121314 |
//create self.searchcontroller = [[ Uisearchcontroller alloc] Initwithsearchresultscontroller:nil]; //searchbar frame Self.searchController.searchBar.frame = CGRectMake (0, 0, +); //If you need to dim false self.searchcontroller.searchbar.showscancelbutton = YES; /**< Cancel button */ Self.searchController.searchResultsUpdater = self; /**< Show search results for VC */ self.searchcontroller.active = YES; /**< Search results Display */ |
The code associated with TableView is as follows:
?
12345678910111213 |
//tableview self.tableview = [[UITableView alloc] Initwithframe:cgrectmake (0, 20, Self.view.bounds.size.width, self.view.bounds.size.height-20) Style:uitableviewstyleplain]; [self.view AddSubview:self.tableView]; self.tableview.delegate = self; self.tableview.datasource = self; [self.tableview Registerclass:[uitableviewcell class forcellreuseidentifier:@ //Place Searchbar on TableView head view |
The Uisearchresultsupdating protocol method code is as follows:
?
1234567891011121314 |
-( void ) Updatesearchresultsforsearchcontroller: (Uisearchcontroller *) Searchcontroller { //initialize an array of stored search results self.arrofseachresults = [Nsmutablearray array]; //get the keyword nspredicate *predicate = [nspredicate predicatewithformat:@ "self contains[c]%@" //Filter the contents of the array with keywords, put the filtered contents into the result array //The completion of data filtering and storage after refreshing tableview. [self.tableview Reloaddata]; } |
TableView's DataSource
?
1234567891011 |
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // 显示搜索结果时 if (self.searchController.active) { //以搜索结果的个数返回行数 return self.arrOfSeachResults.count; } //没有搜索时显示所有数据 return self.arrOfSeachBoxes.count; } |
?
1234567891011121314151617181920212223242526272829303132333435 |
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@
"pool"
];
// 显示搜索结果时
if (self.searchController.active) {
// 原始搜索结果字符串.
NSString *originResult = self.arrOfSeachResults[indexPath.row];
// 获取关键字的位置
NSRange range = [originResult rangeOfString:self.searchController.searchBar.text];
// 转换成可以操作的字符串类型.
NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:originResult];
// 添加属性(粗体)
[attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:range];
// 关键字高亮
[attribute addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
// 将带属性的字符串添加到cell.textLabel上.
[cell.textLabel setAttributedText:attribute]; cell.textLabel.text = self.arrOfSeachResults[indexPath.row];
}
else {
cell.textLabel.text = self.arrOfSeachBoxes[indexPath.row];
}
return cell;
}
|
Ios_searchbar Search bar and keyword highlighting