I've implemented UISearchControl (iOS8 version which is slightly different then previous ones). It seems to be firing correctly when I type stuff in according to the NSLog statement seen below, only issue is it the UITableView actually never gets updated, and I added a NSLog to the } else { part of the numberOfRowsInSection to confirm that it's not called like so:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return self.objects.count;
} else {
// NOT BEING FIRED WHEN STUFF IS TYPED IN SEARCH BAR?
NSLog(#"Search Results Returned in TableView");
return self.searchResults.count;
}
}
Although these methods are firing fine...and updating the searchResults array correctly according to the NSLog added in the updateFilter method:
#pragma mark - UISearchResultsUpdating
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = [self.searchController.searchBar text];
[self updateFilteredContentForSaleName:searchString];
// ASSUMING THIS IS WHAT CAUSES TABLEVIEW TO REFRESH, BUT ISNT REFRESHING IT WITH NEW ARRAY?
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
}
#pragma mark - Content Filtering
- (void)updateFilteredContentForSaleName:(NSString *)saleName {
[self.searchResults removeAllObjects];
for (PFObject *sale in self.objects)
{
NSString *saleTitle = [sale objectForKey:#"name"];
if ([[saleTitle lowercaseString] hasPrefix:[saleName lowercaseString]])
{
[self.searchResults addObject:sale];
}
}
// THIS LOG SHOWS SEARCH RESULTS CORRECTLY HOW THEY SHOULD BE, JUST NO UPDATE TO UITABLEVIEW
NSLog(#"%#", self.searchResults);
}
But simply no update to the tableview...
Any idea why this is? Am I calling the refresh wrong here?:
[((UITableViewController *)self.searchController.searchResultsController).tableView reloadData];
I've tried PFQueryTableViewController * too since that's essentially what I'm using for actual view controller, but no luck.
EDIT
Here is the code used to create the UISearchControl
#interface LocalSalesViewController () <UISearchResultsUpdating>
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults; // Filtered search results
#end
#implementation LocalSalesViewController
- (id)initWithCoder:(NSCoder *)aCoder {
self = [super initWithCoder:aCoder];
if (self) {
self.parseClassName = #"Sales";
self.pullToRefreshEnabled = YES;
self.paginationEnabled = YES;
self.objectsPerPage = 25;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.searchResults = [NSMutableArray array];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.tableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
}
Related
I want to implement search controller like gmail application,
OR I want to implement like this example
Image 1 It shows normal inbox with search controller button
Image 2 After clicking on search button It will expand show like image 2. Here we can enter the words...etc
Image 3 Here whatever we enter, depending upon text it shows in list, and when we click on it, it will navigate to detail view.
same thing I want to implement.
Only thing is that, when I will start typing in search controller, one API will call i.e search, then depending upon text entered in search, it will take as parameter and it will show data in list (table view). this data will come from API response.
And when I click on any result, it has to move detail view.
Anybody, can help me.
I am totally new in iOS. Just now I started learning of iOS. Plz help me for this.
Here is .h file
#import <UIKit/UIKit.h>
#interface PDSearchExampleTableViewController : UITableViewController
{
BOOL searching;
}
#property (strong, nonatomic) UISearchBar *searchBar;
#property (strong, nonatomic) NSMutableArray *sampleDataArray;
#property (strong, nonatomic) NSMutableArray *filteredSampleDataArray;
- (IBAction)searchButtonClicked:(id)sender;
#end
Here is .m file
#import "PDSearchExampleTableViewController.h"
#interface PDSearchExampleTableViewController () <UISearchDisplayDelegate, UISearchBarDelegate>
#end
#implementation PDSearchExampleTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
_searchBar.delegate = self;
_sampleDataArray = [[NSMutableArray alloc] init];
_filteredSampleDataArray = [[NSMutableArray alloc] init];
[_sampleDataArray addObject:#"one"];
[_sampleDataArray addObject:#"two"];
[_sampleDataArray addObject:#"three"];
[_sampleDataArray addObject:#"four"];
[_sampleDataArray addObject:#"five"];
[_sampleDataArray addObject:#"six"];
[_sampleDataArray addObject:#"seven"];
[self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
if (searching) {
return [_filteredSampleDataArray count];
} else {
return [_sampleDataArray count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"sampleSearchCell" forIndexPath:indexPath];
if (searching) {
cell.textLabel.text = [_filteredSampleDataArray objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [_sampleDataArray objectAtIndex:indexPath.row];
}
return cell;
}
- (IBAction)searchButtonClicked:(id)sender {
self.navigationItem.rightBarButtonItem = nil;
_searchBar = [[UISearchBar alloc] init];
_searchBar.delegate = self;
_searchBar.placeholder = #"Search Sample Data";
[_searchBar sizeToFit];
self.navigationItem.titleView = _searchBar;
[_searchBar becomeFirstResponder];
[_searchBar.window makeKeyAndVisible];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
[_searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searching = NO;
[self.tableView reloadData];
self.navigationItem.titleView = nil;
UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:#selector(searchButtonClicked:)];
[_searchBar setShowsCancelButton:NO];
[_searchBar resignFirstResponder];
self.navigationItem.rightBarButtonItem = rightBarButton;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[_filteredSampleDataArray removeAllObjects];
if ([searchText length] != 0) {
searching = YES;
[self searchData];
} else {
searching = NO;
}
[self.tableView reloadData];
}
- (void)searchData {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#", _searchBar.text];
NSArray *tempArray = [_sampleDataArray filteredArrayUsingPredicate:predicate];
NSLog(#"%#", tempArray);
_filteredSampleDataArray = [NSMutableArray arrayWithArray:tempArray];
}
Follow the below steps, it will work definitely not exactly as same as your screenshots.
STEP 1: Create a navigation button on the navigation bar and add image button of a search for it. This can be done by using a storyboard or using programmatically.
Give action to that button,
- (IBAction)searchButtonAction:(id)sender {
SearchViewController *vc=[self.storyboard instantiateViewControllerWithIdentifier:#"id1"];
[self.navigationController pushViewController:vc animated:YES];
}
after clicking this button, it will navigate to SearchViewController view.
See storyboard, design like below image
and write below code in SearchViewController,
Create IBOutlet of textField and give action to the search button, and add tableView and add delegates and data source for it.
#property (weak, nonatomic) IBOutlet UITextField *seachTextField;
#property (weak, nonatomic) IBOutlet UITableView *tableview1;
and
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[_seachTextField resignFirstResponder];
return YES;
}
// This method asks the delegate whether the specified text should be replaced in the text view.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSLog(#"Search String is : %#",_seachTextField.text);
NSString *dataFromSearchTextField=[NSString stringWithFormat:#"%#",_seachTextField.text];
return YES;
}
- (IBAction)searchButtonAction:(id)sender {
// call method for which takes search string
[self ApiMethodCall:_seachTextField.text];
}
//After clicking on search button, below method is called i.e t API is called
-(void)ApiMethodCall:(NSString *)searchText
{
// call your API with parameters
// you will get JSON
}
that's it, now it is your turn. Take data from JSON which may contain arrays and dictionaries. Simply do JSON parsing and write table view data source and delegate methods and show data.
You can follow my blog link . Have implemented in both objective C and Swift.
Swift
Objective C
Creating a search view, this is the code that i did for the main search view.
What happens is if i dont search/filter, the uisearchbar gets dismissed when segueing. but if i search/filter then the uisearchbar stays on the nav bar when seguing.
- (void)viewDidLoad {
[super viewDidLoad];
// There's no transition in our storyboard to our search results tableview or navigation controller
// so we'll have to grab it using the instantiateViewControllerWithIdentifier: method
UINavigationController *searchResultsController = [[self storyboard] instantiateViewControllerWithIdentifier:#"CompanySearchResultsNavigationController"];
// Our instance of UISearchController will use searchResults
self.searchController = [[UISearchController alloc] initWithSearchResultsController:searchResultsController];
// The searchcontroller's searchResultsUpdater property will contain our tableView.
self.searchController.searchResultsUpdater = self;
self.searchController.hidesNavigationBarDuringPresentation = NO;
// The searchBar contained in XCode's storyboard is a leftover from UISearchDisplayController.
// Don't use this. Instead, we'll create the searchBar programatically.
self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.navigationItem.titleView = self.searchController.searchBar;
self.definesPresentationContext = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.objects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
CompanySearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"searchCell" forIndexPath:indexPath];
cell.productImageView.file = (PFFile *)object[#"profileImage"];
cell.productImageView.layer.cornerRadius = cell.productImageView.frame.size.width / 2;
cell.productImageView.clipsToBounds = YES;
[cell.productImageView loadInBackground];
cell.companyNameLabel.text = object[#"username"];
return cell;
}
#pragma mark - UISearchControllerDelegate & UISearchResultsDelegate
// Called when the search bar becomes first responder
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
// Set searchString equal to what's typed into the searchbar
NSString *searchString = self.searchController.searchBar.text;
[self updateFilteredContentForAirlineName:searchString];
// If searchResultsController
if (self.searchController.searchResultsController) {
UINavigationController *navController = (UINavigationController *)self.searchController.searchResultsController;
// Present SearchResultsTableViewController as the topViewController
CompanySearchResultsTableViewController *vc = (CompanySearchResultsTableViewController *)navController.topViewController;
// Update searchResults
vc.searchResults = self.searchResults;
// And reload the tableView with the new data
[vc.tableView reloadData];
}
}
// Update self.searchResults based on searchString, which is the argument in passed to this method
- (void)updateFilteredContentForAirlineName:(NSString *)companyName
{
if (companyName == nil) {
// If empty the search results are the same as the original data
self.searchResults = [self.objects mutableCopy];
} else {
NSMutableArray *searchResults = [[NSMutableArray alloc] init];
// Else if the airline's name is
for (PFObject *company in self.objects) {
if ([company[#"username"] containsString:companyName]) {
// NSString *str = [NSString stringWithFormat:#"%#", company[#"username"]];
// [searchResults addObject:str];
PFObject *searchedObject = company;
[searchResults addObject:searchedObject];
NSLog(#"Searched: %#",searchedObject[#"username"]);
}
self.searchResults = searchResults;
}
}
}
In your AirlineTableViewController, override [UIViewController prepareForSegue]:
- (void)prepareForSegue:(UIStoryboardSegue *)segue
sender:(id)sender {
[self.searchController setActive:NO];
}
I have been trying to implement UISearchController by following stackoverflow thread:
How to implement UISearchController with objective c
and Apples's documentation, but can't make it working. When the initial controller (EVTSearchViewController which is defined as UIViewController) that complies with UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating, UITableViewDelegate
(I needed to make it compliant with UITableViewDelegate too, since I am making it a delegate of the other UITableViewController type EVTSearchResultsViewController *resultsControllers tableView) delegates is presented, I see my .xib with the UISearchBar and UITableView, I click the search bar and start typing:
When I type one letter, search bar disappears and nothing is shown:
First, I do not want the search bar to disappear. Second, updateSearchResultsForSearchController seems not to be called at all since NSLog() set up there does not produce any output when I am typing in the search bar.
I have .xib for the EVTSearchViewController and it has a UISearchBar that I am connecting to the respective property: IBOutlet UISearchBar *searchBar which is then made to point to the UISearchControllers' searchBar:
self.searchBar = self.searchController.searchBar
There is also UITableView that I put below the UISearchBar in the .xib. Another controller that I am using inside EVTSearchViewController is EVTSearchResultsViewController, it is UITableViewController and it does not have its .xib.
Below is the code for viewDidLoad and updateSearchResultsForSearchController methods:
- (void)viewDidLoad
{
_resultsController = [[EVTSearchResultsViewController alloc] init];
_searchController = [[UISearchController alloc] initWithSearchResultsController:_resultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = nil;
[self.searchController.searchBar sizeToFit];
self.searchBar = self.searchController.searchBar;
// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.resultsController.tableView.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = YES; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES; // know where you want UISearchController to be displayed
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// update the filtered array based on the search text
NSString *searchText = searchController.searchBar.text;
NSLog(#"searchText: %#", searchText);
if (searchText == nil) {
// If empty the search results are the same as the original data
self.searchResults = [[[EVTItemStore sharedStore] allItems] mutableCopy];
} else {
NSMutableArray *searchResults = [[NSMutableArray alloc] init];
NSArray *allEvents = [[EVTItemStore sharedStore] allItems];
NSLog(#"allEvents: %#", allEvents);
for (EVTItem *event in allEvents) {
/*if ([event.number containsString:searchText] || [[phoneMO.closrr_id filteredId] containsString:searchText] || [[phoneMO.contact.fullname lowercaseString] containsString:[searchText lowercaseString]]) {
[searchResults addObject:phoneMO];
}*/
if ([event.eventName containsString:searchText]) {
[searchResults addObject:event];
}
}
self.searchResults = searchResults;
}
// hand over the filtered results to our search results table
EVTSearchResultsViewController *resultsController = (EVTSearchResultsViewController *)self.searchController.searchResultsController;
resultsController.filteredEvents = self.searchResults;
[resultsController.tableView reloadData];
}
The respective #properties defined in EVTSearchViewController:
#interface EVTSearchViewController ()
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) EVTSearchResultsViewController *resultsController;
#property (nonatomic, strong) NSMutableArray *searchResults;
// For state restoration
#property BOOL searchControllerWasActive;
#property BOOL searchControllerSearchFieldWasFirstResponder;
#end
Then, here is the code for EVTSearchResultsViewController:
#import "EVTSearchResultsViewController.h"
#implementation EVTSearchResultsViewController
- (instancetype)init
{
// Call the superclass's designated initializer
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:#"UISearchViewCell"];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.filteredEvents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:#"UISearchViewCell"
forIndexPath:indexPath];
cell.textLabel.text = self.filteredEvents[indexPath.row];
return cell;
}
#end
The methods of EVTSearchResultsViewController above are not called at all which makes look very strange for me, why do we need it at all, then?
I tried to set UISearchBar the way Apple docs recommend:
self.resultsTableView.tableHeaderView = self.searchController.searchBar;
but it gives me a non-responsive search box, so when pressing nothing happens.
Could anyone, please, help with resolving the question. The other question linked above can also be clarified then. Thank you.
So, I solved the issue and implemented basic search with UISearchController. Here is what we need to do to implement the basic search:
Create two UITableViewControllers classes with NO .xib files. Yes, there should be no .xib files and we are just creating two classes. In the code below their names are EVTSearchViewController and EVTSearchResultsViewController.
Make one of the controllers to comply with the delegates: <UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating>
Here is the code for the header file of EVTSearchViewController:
#import <UIKit/UIKit.h>
#interface EVTSearchViewController : UITableViewController <UISearchBarDelegate, UISearchControllerDelegate, UISearchResultsUpdating>
#end
Here is the EVTSearchResultsViewController's header:
#import <UIKit/UIKit.h>
#interface EVTSearchResultsViewController : UITableViewController
#property (nonatomic, strong) NSMutableArray *filteredEvents;
#end
The NSMutableArray *filteredEvents will hold the results of the search. We should NOT implement any of the UITableViewController delegate methods in EVTSearchViewController.m, but should in EVTSearchResultsViewController.m.
Here is the top part of EVTSearchViewController:
#import "EVTSearchViewController.h"
#import "EVTSearchResultsViewController.h"
// Importing the class that stores `EVTItem` object classes
#import "EVTItemStore.h"
#import "EVTItem.h"
#interface EVTSearchViewController ()
#property (nonatomic, strong) UISearchController *searchController;
// We created this class
#property (nonatomic, strong) EVTSearchResultsViewController *resultsController;
// array to hold the results of the search
#property (nonatomic, strong) NSMutableArray *searchResults;
#end
Here is the code for EVTSearchViewController's viewDidLoad: method:
- (void)viewDidLoad
{
[super viewDidLoad];
self.resultsController = [[EVTSearchResultsViewController alloc] init];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:self.resultsController];
self.searchController.searchResultsUpdater = self;
self.searchController.searchBar.placeholder = nil;
[self.searchController.searchBar sizeToFit];
// This line of code is very important. Here we are using apple docs'
// suggestion. UITableViewController has tableView property, so
// we are just setting tableView`s header to apples' UISearchController`s' `searchBar property
self.tableView.tableHeaderView = self.searchController.searchBar;
self.searchController.delegate = self;
// default is YES
self.searchController.dimsBackgroundDuringPresentation = YES;
// so we can monitor text changes + other changes
self.searchController.searchBar.delegate = self;
// know where you want UISearchController to be displayed
self.definesPresentationContext = YES;
}
Then we add to EVTSearchViewController the following method:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// update filtered array based on the search text
NSString *searchText = searchController.searchBar.text;
if (searchText == nil) {
// If empty the search results should be the same as the original data
self.searchResults = [[[EVTItemStore sharedStore] allItems] mutableCopy];
} else {
NSMutableArray *searchResults = [[NSMutableArray alloc] init];
// [[EVTItemStore sharedStore] allItems] message retrieves
// all of the objects that I have in datastore EVTItemStore
NSArray *allEvents = [[EVTItemStore sharedStore] allItems];
// EVTItem class has a property eventName which we are using
// for searching, then adding it to our searchResults array
for (EVTItem *event in allEvents) {
if ([event.eventName containsString:searchText]) {
[searchResults addObject:event];
}
}
self.searchResults = searchResults;
}
// hand over the filtered results to our search results table
EVTSearchResultsViewController *resultsController = (EVTSearchResultsViewController *)self.searchController.searchResultsController;
resultsController.filteredEvents = self.searchResults;
[resultsController.tableView reloadData];
}
Another controller's EVTSearchResultsViewController #implementation part looks like this:
#implementation EVTSearchResultsViewController
- (instancetype)init
{
// Call the superclass's designated initializer
self = [super initWithStyle:UITableViewStylePlain];
if (self) {
}
return self;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.filteredEvents count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:#"UISearchViewCell"
forIndexPath:indexPath];
EVTItem *event = self.filteredEvents[indexPath.row];
cell.textLabel.text = event.eventName;
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:#"UISearchViewCell"];
}
#end
That's it. If we need to further customize our cells, we should be able to do it by making UISearchViewCell.xib for EVTSearchResultsViewController, and using the following viewDidLoad instead:
- (void)viewDidLoad
{
[super viewDidLoad];
// Load the NIB file
UINib *nib = [UINib nibWithNibName:#"UISearchViewCell" bundle:nil];
// Register this NIB which contains the cell
[self.tableView registerNib:nib forCellReuseIdentifier:#"UISearchViewCell"];
}
My Question is this. Why is the filtered table view showing rooms, after I start typing in the search bar that are not present when printing the filtered array to the console. I thought it might be that the table view cells are being reused so set the cell label text to nil to ensure the text gets reset in tableviewcellforindex: method , all to no avail. Can anyone help?
This is my Table View Controller that acts as the data source and delegate for for both my standard tableview and filtered tableview
#import <UIKit/UIKit.h>
#import "Rooms.h"
#interface RoomsTableViewController : UITableViewController
<UISearchControllerDelegate,UISearchResultsUpdating,UISearchBarDelegate,UITableViewDelegate>
#property (strong,nonatomic) NSMutableArray *roomList;
#property (strong,nonatomic) NSMutableArray *orderedRoomList;
#property (strong,nonatomic) NSMutableArray *filteredRooms;
#property (strong,nonatomic) UITableViewController *searchResultsController;
#property (strong,nonatomic) UISearchController *searchController;
#end
#import "RoomsTableViewController.h"
#interface RoomsTableViewController ()
#property BOOL searchControllerWasActive;
#property BOOL searchControllerSearchFieldWasFirstResponder;
#end
The implementation file
#implementation RoomsTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
//sort the room list into filetred by alpha numeric A10 before C1 example this will eventually be done on the server
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) {
return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch];
}];
self.orderedRoomList = (NSMutableArray*)[self.roomList sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
self.searchResultsController= [[UITableViewController alloc]initWithStyle:UITableViewStylePlain];
self.searchController = [[UISearchController alloc]initWithSearchResultsController:self.searchResultsController];
self.searchController.searchResultsUpdater=self;
[self.searchController.searchBar sizeToFit];
self.tableView.tableHeaderView=self.searchController.searchBar;
//set up the data source and delegate of this new table view to be this (roomsTableviewcontroller) view controller
self.searchResultsController.tableView.delegate=self;
self.searchResultsController.tableView.dataSource=self;
self.searchController.delegate=self;
self.searchController.dimsBackgroundDuringPresentation=NO;
self.searchController.searchBar.delegate=self;
self.definesPresentationContext=YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
//restore the search controllers active state
if (self.searchControllerWasActive) {
self.searchController.active = self.searchControllerWasActive;
_searchControllerWasActive=NO;
if (self.searchControllerSearchFieldWasFirstResponder) {
[self.searchController.searchBar becomeFirstResponder];
_searchControllerSearchFieldWasFirstResponder=NO;
}
}
}
-(void)searchBarBookmarkButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
#pragma mark - UISearchControllerDelegate
- (void)willPresentSearchController:(UISearchController *)searchController {
// do something before the search controller is presented
self.navigationController.navigationBar.translucent = YES;
}
-(void)willDismissSearchController:(UISearchController *)searchController
{
self.navigationController.navigationBar.translucent = NO;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView==self.tableView) {
return [self.orderedRoomList count];
}else{
return [self.filteredRooms count];
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 71;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellReuseIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier];
if (cell==nil) {
cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseIdentifier];
}
Rooms *room = (tableView==self.tableView)? [self.orderedRoomList objectAtIndex:indexPath.row]: [self.filteredRooms objectAtIndex:indexPath.row];
cell.textLabel.text=nil;
NSString *labelString = [NSString stringWithFormat:#"%# %#",room.name,room.roomDescription];
cell.textLabel.text=labelString;
return cell;
}
Below is a photo of the table view in the simulator and a screen print of the check to see if the filtered array has indeed worked correctly as it has. You can see that C3 is not listed as being part of the filtered array but it still appears on screen.
I am using UISearchbar in tableview controller in storyboard.
And searchbar returnKeyType is UIReturnKeySearch.
Its working fine with iOS7 but returnKeyType is not working with iOS8.
in iOS8, return key appears every time in keyboard.
I tried to set returnkeytype in viewDidLoad method of controller too.
What I need to do to set returnKeyType = UIReturnKeySearch in iOS8?
I think you can go with your hard codded logic for right now.
I will update if I will get better solution for your problem.
-(void)viewDidLoad {
[self setReturnKeyTypeSearchForView:searchBar];
}
-(void)setReturnKeyTypeSearchForView:(UIView *)view
{
for (id subView in view.subviews) {
if ([subView isKindOfClass:[UITextField class]]) {
[subView setReturnKeyType:UIReturnKeySearch];
}
else {
[self setReturnKeyTypeSearchForView:subView];
}
}
if ([view isKindOfClass:[UITextField class]]) {
[(UITextField *)view setReturnKeyType:UIReturnKeySearch];
}
}
Try making IBOutlet of your SearchBar
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
and add the below line code to your viewDidLoad Method
// if u want Done return key and change accordingly.
_searchBar.returnKeyType = UIReturnKeyDone;
SearchViewController.h
//
#import <UIKit/UIKit.h>
#interface SearchViewController : UIViewController
<UISearchBarDelegate, UITableViewDataSource> {
NSMutableArray *tableData;
UIView *disableViewOverlay;
UITableView *theTableView;
UISearchBar *theSearchBar;
}
#property(retain) NSMutableArray *tableData;
#property(retain) UIView *disableViewOverlay;
#property (nonatomic, retain) IBOutlet UITableView *theTableView;
#property (nonatomic, retain) IBOutlet UISearchBar *theSearchBar;
- (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active;
#end
SearchViewController.m
//
#import "SearchViewController.h"
#implementation SearchViewController
#synthesize tableData;
#synthesize disableViewOverlay;
#synthesize theSearchBar;
#synthesize theTableView;
// Initialize tableData and disabledViewOverlay
- (void)viewDidLoad {
[super viewDidLoad];
self.tableData =[[NSMutableArray alloc]init];
self.disableViewOverlay = [[UIView alloc]
initWithFrame:CGRectMake(0.0f,44.0f,320.0f,416.0f)];
self.disableViewOverlay.backgroundColor=[UIColor blackColor];
self.disableViewOverlay.alpha = 0;
}
// Since this view is only for searching give the UISearchBar
// focus right away
- (void)viewDidAppear:(BOOL)animated {
[self.theSearchBar becomeFirstResponder];
[super viewDidAppear:animated];
}
#pragma mark -
#pragma mark UISearchBarDelegate Methods
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
// We don't want to do anything until the user clicks
// the 'Search' button.
// If you wanted to display results as the user types
// you would do that here.
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
// searchBarTextDidBeginEditing is called whenever
// focus is given to the UISearchBar
// call our activate method so that we can do some
// additional things when the UISearchBar shows.
[self searchBar:searchBar activate:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
// searchBarTextDidEndEditing is fired whenever the
// UISearchBar loses focus
// We don't need to do anything here.
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
// Clear the search text
// Deactivate the UISearchBar
searchBar.text=#"";
[self searchBar:searchBar activate:NO];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// Do the search and show the results in tableview
// Deactivate the UISearchBar
// You'll probably want to do this on another thread
// SomeService is just a dummy class representing some
// api that you are using to do the search
NSArray *results = [SomeService doSearch:searchBar.text];
[self searchBar:searchBar activate:NO];
[self.tableData removeAllObjects];
[self.tableData addObjectsFromArray:results];
[self.theTableView reloadData];
}
// We call this when we want to activate/deactivate the UISearchBar
// Depending on active (YES/NO) we disable/enable selection and
// scrolling on the UITableView
// Show/Hide the UISearchBar Cancel button
// Fade the screen In/Out with the disableViewOverlay and
// simple Animations
- (void)searchBar:(UISearchBar *)searchBar activate:(BOOL) active{
self.theTableView.allowsSelection = !active;
self.theTableView.scrollEnabled = !active;
if (!active) {
[disableViewOverlay removeFromSuperview];
[searchBar resignFirstResponder];
} else {
self.disableViewOverlay.alpha = 0;
[self.view addSubview:self.disableViewOverlay];
[UIView beginAnimations:#"FadeIn" context:nil];
[UIView setAnimationDuration:0.5];
self.disableViewOverlay.alpha = 0.6;
[UIView commitAnimations];
// probably not needed if you have a details view since you
// will go there on selection
NSIndexPath *selected = [self.theTableView
indexPathForSelectedRow];
if (selected) {
[self.theTableView deselectRowAtIndexPath:selected
animated:NO];
}
}
[searchBar setShowsCancelButton:active animated:YES];
}
#pragma mark -
#pragma mark UITableViewDataSource Methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"SearchResult";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
}
id *data = [self.tableData objectAtIndex:indexPath.row];
cell.textLabel.text = data.name;
return cell;
}
#pragma mark -
#pragma mark Memory Management Methods
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[theTableView release], theTableView = nil;
[theSearchBar release], theSearchBar = nil;
[tableData dealloc];
[disableViewOverlay dealloc];
[super dealloc];
}
#end
Building a SearchView with UISearchBar and UITableView
this might helps you :)
I'm not sure if I understood your question correctly. You want to have "search" button instead of "return" button, right? There is a new SearchController in ios 8, give it a try:
YourTableViewController.h
#interface YourTableViewController : UITableViewController<UISearchResultsUpdating>
#end
And now the implementation:
YourTableViewController.m
- (void)viewDidLoad {
// initializing with the same controller as presenting
UISearchController *searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
searchController.searchResultsUpdater = self;
searchController.searchBar.frame = CGRectMake(searchController.searchBar.frame.origin.x, searchController.searchBar.frame.origin.y, searchController.searchBar.frame.size.width, 44.0f);
searchController.dimsBackgroundDuringPresentation = NO;
searchController.searchBar.delegate = self;
searchController.searchBar.returnKeyType = UIReturnKeySearch; //should be search by default.. you can change to whatever you want.
// adding searchBar into HeaderView
self.tableView.tableHeaderView = searchController.searchBar;
// just to be able to present results on the same controller
self.definesPresentationContext = YES;
}
You also have to implement method from UISearchResultsUpdating protocol:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
// you can leave it blank
}
EDIT: If it is not what you were looking for please comment, so I can update my answer accordingly
try this in viewDidLoad:
UITextField *txfSearchField = [yourSearchbar valueForKey:#"_searchField"];
if([txfSearchField conformsToProtocol:#protocol(UITextInputTraits)]) {
[txfSearchField setReturnKeyType:UIReturnKeyDefault];
}