How to implement Ios_searchbar search bar and keyword highlighting _ios

Source: Internet
Author: User

The effect of the search box demonstrates:

This is the so-called search box, then let's look at how to use the code to implement this function.

The data I use is a Hero League list of heroes, is a TXT file of JSON data, the processing code for JSON data is as follows:

Gets the path of the file path
nsstring *path = [[NSBundle mainbundle] pathforresource:@ "heros" oftype:@ "txt"];
Convert the files under the path to NSData data
nsdata *data = [NSData Datawithcontentsoffile:path];
Parses the resulting NSData data into JSON and returns an array of result
ids results = [nsjsonserialization jsonobjectwithdata:data options: Nsjsonreadingmutablecontainers Error:nil];

Let's look at the hierarchical relationship of data:


Here's the explanation, this hierarchical relationship is obtained by formatting the Web page with an online code, and the data we do in the last step is to process the raw data, get an array of results, and his hierarchy and formatting, so that the data can be processed further according to the hierarchical relationships on the formatted Web page. Put what you need into an array or a dictionary (and, of course, print the result directly to see the hierarchy and personal habits).

So what we need is the value of nick in the dictionary, and we'll take it out and put it in the array, which defines it as an attribute, which is used in other methods.

Put the contents of the search scope into the array for
(nsdictionary *diction in result) {
  [self.arrofseachboxes addobject:diction[@ "Nick"]];
 }

Next we create a uitableview to display the data, and the class to use for the search bar is to UISearchController first see how to create:

The system's annotations make it clear that if you want to display search results on the current page, the parameters of this method are filled nil, and for convenience, declare a UISearchController property

@property (nonatomic, retain) Uisearchcontroller *searchcontroller;

The next step is to create

Nil indicates that search results are displayed on the current page
self.searchcontroller = [[Uisearchcontroller alloc] initwithsearchresultscontroller:nil];

The Uisearchcontroller header file is placed in the very front position of a property


According to the literal meaning, we can guess 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.

-(void) Updatesearchresultsforsearchcontroller: (Uisearchcontroller *) Searchcontroller;

The header file is shown in the following illustration:

---------here is the beautiful dividing line---------

The above has a list of all the classes and methods about the search bar, and let's take a look at it.

All of the defined properties are as follows:

Ns_assume_nonnull_begin
@interface Viewcontroller () <uitableviewdelegate, Uitableviewdatasource, Uisearchresultsupdating>
@property (nonatomic, retain) nsmutablearray *arrofseachboxes;/**< search Scope * *
Property (Nonatomic, retain) nsmutablearray *arrofseachresults;/**< search Results *
/@property (nonatomic, retain) Uisearchcontroller *searchcontroller;
@property (nonatomic, retain) UITableView *tableview;
@end
Ns_assume_nonnull_end

Data processing related code is as follows:

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];
Put the contents of the search scope into the array for
(nsdictionary *dic in result) {
 [self.arrofseachboxes addobject:dic[@ "Nick"]];
}

The relevant code for creating and Uisearchcontroller is as follows:

Create
Self.searchcontroller = [[Uisearchcontroller alloc] initwithsearchresultscontroller:nil];

Searchbar frame
self.searchController.searchBar.frame = CGRectMake (0, 0,);

Whether it is necessary to dim Self.searchController.dimsBackgroundDuringPresentation = False in the input search content
;

Self.searchController.searchBar.showsCancelButton = yes;/**< Cancel button * *

Self.searchController.searchResultsUpdater = self;/**< Display search results VC/

self.searchController.active = yes;/** < search results show * *

The code associated with TableView is as follows:

TableView
Self.tableview = [[UITableView alloc] Initwithframe:cgrectmake (0, 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:@ "Pool"];

Place the Searchbar in the TableView head view 
self.tableView.tableHeaderView = Self.searchController.searchBar;

The Uisearchresultsupdating protocol method code is as follows:

-(void) Updatesearchresultsforsearchcontroller: (Uisearchcontroller *) Searchcontroller {

//Initialize the array
that stores search results Self.arrofseachresults = [Nsmutablearray array];

Gets the keyword
nspredicate *predicate = [nspredicate predicatewithformat:@ "SELF contains[c]%@", SearchController.searchBar.text];

Filter the contents of the array with the keyword, and put the filtered content into the result array
self.arrofseachresults = [[Self.arrofseachboxes filteredarrayusingpredicate: predicate] mutablecopy];

After filtering and storing data, refresh TableView.
[Self.tableview reloaddata];
}

TableView's DataSource

-(Nsinteger) TableView: (UITableView *) TableView numberofrowsinsection: (nsinteger) Section {

//Display search results if
( self.searchController.active) {

 //returns the number of rows with the number of search results return
 self.arrOfSeachResults.count;
}
 Show all data when not searching return
 Self.arrOfSeachBoxes.count;
-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) IndexPath {

UITableViewCell *cell = [TableView dequeuereusablecellwithidentifier:@ "Pool"];
Display search results if (self.searchController.active) {//original search result string.

NSString *originresult = Self.arrofseachresults[indexpath.row];

Gets the position of the keyword nsrange range = [Originresult rangeOfString:self.searchController.searchBar.text];
Converts to a string type that can be manipulated.

nsmutableattributedstring *attribute = [[Nsmutableattributedstring alloc] initwithstring:originresult];

Add attributes (bold) [attribute Addattribute:nsfontattributename Value:[uifont systemfontofsize:20] range:range];

keywords highlighting [attribute addattribute:nsforegroundcolorattributename Value:[uicolor Redcolor] range:range];
Adds a string with attributes to the Cell.textlabel.

[Cell.textlabel Setattributedtext:attribute];

 Cell.textLabel.text = Self.arrofseachresults[indexpath.row];

  else {cell.textLabel.text = Self.arrofseachboxes[indexpath.row];
} return cell; }

Summarize

The above is how to achieve the iOS search bar and search keyword highlighting all the content, interested students can do their own hands-on operation to achieve, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.