[Learning ios: UI series] (UISearchBar, UISearchDisplayController), UISearchController (New Features of iOS8), and uisearchbarios8

Source: Internet
Author: User

[Learning ios: UI series] (UISearchBar, UISearchDisplayController), UISearchController (New Features of iOS8), and uisearchbarios8

1. UISearchBar (the effect is as follows :)


① Create a UISearchBar object

// Initialize, define frame UISearchBar * bar = [[UISearchBar alloc] initWithFrame: CGRectMake (0, 50, self. view. frame. size. width, 80)]; // Add it to the Controller view [self. view addSubview: bar];
② UISerachBar attributes

// AutocapitalizationType: contains four types, but sometimes the keyboard shields this type. // 1. autocapitalizationType ---- automatically set the case sensitivity of the input text object. bar. autocapitalizationType = UITextAutocapitalizationTypeWords; // 2. autocorrectionType ---- automatically corrects input text objects by bar. autocorrectionType = UITextAutocorrectionTypeYes; // 3. set title bar. prompt = @ "all contacts"; // 4. set the color bar. tintColor = [UIColor purpleColor]; // render the color bar. barTintColor = [UIColor orangeColor]; // search bar color. backgro UndColor = [UIColor purpleColor]; // background color, because the frosted glass effect (transulent ). // 5. translucent ---- specifies whether the control has a bar with a perspective effect. translucent = YES; // 6. scopeButtonTitles (range: buttonTitle) bar. scopeButtonTitles = @ [@ "exact search", @ "fuzzy search"]; bar. selectedScopeButtonIndex = 1; // use a subscript to specify the default selection column. // 7. control whether the selection bar at the bottom of the search bar is displayed (you must set it to YES to use scopebar) bar. showScopeBar = YES; // 8. set the button bar on the right of the search bar. showsSearchResultsButton = YES; // The Down Arrow bar. showsCancelButton = Y ES; // cancel the button bar. showsBookmarkButton = YES; // bookmark button // 9. prompt bar. placeholder = @ "Search"; // 10. cancel the keyboard operation [searchBar resignFirstResponder]; // 11. set the proxy // UISearchBar to not perform the search action. You must use delegate. After you enter the search text and click the button, the proxy method will complete the search operation. // Delegate the control. The delegate must comply with the UISearchBarDelegate protocol. The default value is nil bar. delegate = self;

③ Protocol method to be implemented by the proxy 

1). Input and edit event processing

– searchBar:textDidChange:– searchBar:shouldChangeTextInRange:replacementText:– searchBarShouldBeginEditing:– searchBarTextDidBeginEditing:– searchBarShouldEndEditing:– searchBarTextDidEndEditing:
2) click the button to handle the event
– searchBarBookmarkButtonClicked:– searchBarCancelButtonClicked:– searchBarSearchButtonClicked:– searchBarResultsListButtonClicked:
3). Click the Scope button to process the event.
– searchBar:selectedScopeButtonIndexDidChange:</span>

2. UISearchDisplayController (Note: iOS8 and above have been deprecated)

Combined with UISearchBar, the following results are achieved to implement the search function.


Tip: the code for detecting the Xcode system version is as follows:

[[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES: NO;
1. Create an object
// Create a UISearchBar object. The object is defined as the property self. searchBar = [[UISearchBar alloc] initWithFrame: CGRectMake (0, 0,320, 40)]; // you can specify the UISearchBar attribute for details. self. searchBar. placeholder = @ "enter province name"; self. searchBar. autocorrectionType = UITextAutocorrectionTypeNo; self. searchBar. autocapitalizationType = UITextAutocapitalizationTypeAllCharacters; self. searchBar. scopeButtonTitles = [NSArray arrayWithObjects: @ "All", @ "A", @ "B", @ "C", @ "D", nil]; self. searchBar. showsScopeBar = YES; self. searchBar. keyboardType = UIKeyboardTypeNamePhonePad; self. searchBar. showsBookmarkButton = YES; // use seachBar as the controller's perspective, View Controller, inheriting UITableViewController self. tableView. tableHeaderView = _ searchBar; // Add UIsearchBar to UIdSearchDispalyController self. displayController = [[UISearchDisplayController alloc] initWithSearchBar: _ searchBar contentsController: self];
Note: searchBar ---- after the searchdisplaycontroller is initialized, The searchbar cannot be modified and is of the readonly attribute.

② Configure UISearchDisplayController attributes

// Active ---- the search interface is visualized. The default value is no and can be set using the setActive method. self. displayController. active = YES; // searchResultsDataSource ---- data source of the search result, proxy object (UITableViewDataSource) self. displayController. searchResultsDataSource = self; // searchResultsDelegate ---- delegate the search result, subject to the UITableViewDelegate self protocol. displayController. searchResultsDelegate = self;
③ Implementation
/* SearchDisplayController has a searchResultsTableView. Therefore, when performing an operation, you must first determine whether it is the tableView of the search result. If it is the data of the search result, is the view of TableView, You need to display the original data. */If (tableView = self. tableView) {return self. dataArray. count;} else {NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "self contains [cd] % @", self. searchBar. text]; self. arr = [[NSMutableArray alloc] initWithArray: [self. dataArray filteredArrayUsingPredicate: predicate]; return self. arr. count ;}

④ Use the delegate method of UISearchDisplayDelegate for search:


1). How to Deal with event changes in search status:

– searchDisplayControllerWillBeginSearch:– searchDisplayControllerDidBeginSearch:– searchDisplayControllerWillEndSearch:– searchDisplayControllerDidEndSearch:


2). Handle tableview events:

– searchDisplayController:didLoadSearchResultsTableView:– searchDisplayController:willUnloadSearchResultsTableView:


3). How to display and hide the tableview event:

– searchDisplayController:willShowSearchResultsTableView:– searchDisplayController:didShowSearchResultsTableView:– searchDisplayController:willHideSearchResultsTableView:– searchDisplayController:didHideSearchResultsTableView:
4). How to handle the event when the search condition changes:
– searchDisplayController:shouldReloadTableForSearchString:– searchDisplayController:shouldReloadTableForSearchScope

3. UISearchController (New Features of iOS8)

The implementation of UISearchController is basically the same as the above, and is applicable to iOS8 and later versions.

Achieve search results


The Code is as follows:

1) create a new controller, inherit from UITableViewController, and define attributes in extension

// Store the original data @ property (nonatomic, retain) NSArray * dataArr; // store the Retrieved Data @ property (nonatomic, retain) NSArray * arr;
2). load data, and load it lazily
-(NSArray *) dataArr {if (! _ DataArr) {self. dataArr = [NSArray arrayWithObjects: @ "Allan", @ "Abbbb", @ "Acccc", @ "Bccccc", @ "Cddddffk", @ "Cddkllll ", @ "Ekkflfl", @ "Ekljljfg", @ "Leslie", @ "Mm", @ "Meinv", @ "Meihi", @ "Catilin", @ "Arron ", @ "211", @ "232", @ "243", @ "264", @ "285", @ "106", @ "311", @ "432 ", @ "543", @ "664", @ "785", @ "806", nil];} return _ dataArr ;}// if the retrieved data is empty, assign the original data value to the Retrieved Data-(NSArray *) arr {if (! _ Arr) {self. arr = self. dataArr;} return _ arr ;}
3. Load UISearchController object
-(Void) viewDidLoad {[super viewDidLoad]; // The cell reuse mechanism calls the system's [self. tableView registerClass: [UITableViewCell class] forCellReuseIdentifier: @ "lock"]; // create a search bar and set itself as the controller UISearchController * searchVC = [[UISearchController alloc] Comment: nil]; // set the rendering color searchVC. searchBar. tintColor = [UIColor orangeColor]; // set the status bar color to searchVC. searchBar. barTintColor = [UIColor orangeColor]; // you can specify whether or not the background is displayed when you start searching. dimsBackgroundDuringPresentation = NO; // adapt to the entire screen [searchVC. searchBar sizeToFit]; // you can specify the searchVC controller that displays the search results. searchResultsUpdater = self; // protocol (UISearchResultsUpdating) // set the search entries of the search controller to the header view self. tableView. tableHeaderView = searchVC. searchBar ;}

4). Methods in the implementation protocol must be implemented.

-(Void) updateSearchResultsForSearchController :( UISearchController *) searchController {// predicate NSPredicate * predicate = [NSPredicate predicateWithFormat: @ "self contains [cd] % @", searchController. searchBar. text]; // store all search-related content to the arr array self. arr = [NSMutableArray arrayWithArray: [self. dataArr filteredArrayUsingPredicate: predicate]; // reload data [self. tableView reloadData];}

5). Set others in UITabelViewController

# Pragma mark-Table view data source // sets the number of partitions-(NSInteger) numberOfSectionsInTableView :( UITableView *) tableView {// Return the number of sections. return 1;} // The number of rows of data in each partition-(NSInteger) tableView :( UITableView *) tableView numberOfRowsInSection: (NSInteger) section {return self. arr. count;}-(UITableViewCell *) tableView :( UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {self. cell = [tableView dequeueReusableCellWithIdentifier: @ "lock" forIndexPath: indexPath]; // set the content displayed on the cell, that is, the searched data self. cell. textLabel. text = self. arr [indexPath. row]; return self. cell ;}
Note: The search box can be empty. (when the search content is empty, all data is returned. If the search content is empty, other modifications are required .)





Related Article

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.