I have an app that was written for iOS 7 the I need to update as UISearchDisplayController is deprecated for UISearchController.
I have went through several tutorials and tried but I cannot get this to work, however I am close.
I am following this pattern.
The problem I am running into is that the pattern I am following loads the data from a son file into an NSDict object, but my data is in an Array. No problem, I just modified the search to use a predicate (I hard coded something for now, get all records with an E in the name).
But I am getting the following error:
2017-09-12 13:01:41.538 Scoular[7644:1963822] -[employee isEqualToString:]: unrecognized selector sent to instance 0x608000105580
2017-09-12 13:01:41.604 Scoular[7644:1963822] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[employee isEqualToString:]: unrecognized selector sent to instance 0x608000105580'
In the SearchResultsTableViewController.m file, at the line
cell.textLabel.text = self.searchResults[indexPath.row];
from the m file below. I am stumped. Any help would be greatly appreciated.
#import "SearchResultsTableViewController.h"
#interface SearchResultsTableViewController ()
#property (nonatomic, strong) NSArray *array;
#end
#implementation SearchResultsTableViewController
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.searchResults count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SearchResultCell" forIndexPath:indexPath];
cell.textLabel.text = self.searchResults[indexPath.row];
return cell;
}
#end
Header File
#import UIKit;
#class EmployeeDetailViewController;
#import <CoreData/CoreData.h>
#import "EmployeeDatabase.h"
#interface EmployeeListViewController : UITableViewController
#end
Implementation File
#import "EmployeeListViewController.h"
#import "EmployeeDetailViewController.h"
#import "SearchResultsTableViewController.h"
#interface EmployeeListViewController () <UISearchResultsUpdating>
#property (nonatomic, strong) NSMutableArray *employees;
#property (nonatomic, strong) UISearchController *searchController;
#property (nonatomic, strong) NSMutableArray *searchResults;
#property (nonatomic,retain) NSMutableDictionary *sections;
#end
#implementation EmployeeListViewController
BOOL isSearching;
//Do I still need this
- (void)awakeFromNib {
if ([[UIDevice currentDevice] userInterfaceIdiom] ==
UIUserInterfaceIdiomPad) {
self.clearsSelectionOnViewWillAppear = NO;
self.preferredContentSize = CGSizeMake(320.0, 600.0);
}
[super awakeFromNib];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Get array of employees and sections
self.employees = [EmployeeDatabase getEmployees];
self.sections = [EmployeeDatabase getSections:_employees];
// 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:#"TableSearchResultsNavController"];
// 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;
// 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.tableView.tableHeaderView = self.searchController.searchBar;
// Set the back bar button
UIBarButtonItem *backButton =
[[UIBarButtonItem alloc] initWithTitle:#"Employees"
style:UIBarButtonItemStylePlain
target:nil
action:nil];
self.navigationItem.backBarButtonItem = backButton;
}
#pragma mark - Table Sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger tmpCount;
if (isSearching) {
tmpCount = 1;
} else {
tmpCount = [[self.sections allKeys] count];
}
return tmpCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.employees count];
}
#pragma mark - Table View
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
}
employee *thisEmployee =
[[self.sections
valueForKey:[[[self.sections allKeys]
sortedArrayUsingSelector:
#selector(localizedCaseInsensitiveCompare:)]
objectAtIndex:indexPath.section]]
objectAtIndex:indexPath.row];
cell.textLabel.text = thisEmployee.fulNme;
return cell;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
NSString *tmpString;
//if (tableView == self.searchDisplayController.searchResultsTableView) {
//tmpString = nil;
//} else {
tmpString =
[[[self.sections allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:
)] objectAtIndex:section];
//}
return tmpString;
}
#pragma mark - Right side bar alphabetical index
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *tmpTitle;
if (isSearching) {
tmpTitle = nil;
} else {
tmpTitle = [[self.sections allKeys]
sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
return tmpTitle;
}
#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
SearchResultsTableViewController *vc = (SearchResultsTableViewController *)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 *)employeeName
{
if (employeeName == nil) {
// If empty the search results are the same as the original data
self.searchResults = [self.employees mutableCopy];
} else {
NSArray *searchResults2 = [[NSMutableArray alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"fulNme contains 'E'"];
searchResults2 = [self.employees filteredArrayUsingPredicate:predicate];
self.searchResults = [searchResults2 mutableCopy];
}
}
#end
In your updateFilteredContentForAirlineName function you are searching from self.employees array which probably contains employee custom class object. For that reason your self.searchResults array also containing same class object.
But in your cellForRowAtIndexPath of SearchResultsTableViewController your are doing cell.textLabel.text = self.searchResults[indexPath.row]; that means you are adding employee object as string in cell.textLabel which causing your app to crash. Instead you can try this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SearchResultCell" forIndexPath:indexPath];
employee *thisEmployee = self.searchResults[indexPath.row];
cell.textLabel.text = thisEmployee.fulNme;
return cell;
}
Related
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 working on Fitness(workout) scheduler app with SWRevealView Controller, which offers side bar menu feature.
I have tried to link one cell from the side bar menu to another Tableview controller, where I have set segue between them.
The segue is fine, but it does not display the text data that I have in the mutable array.
MainViewController.h
#import <UIKit/UIKit.h>
#interface MainViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
#end
MainViewController.m
#import "MainViewController.h"
#import "SWRevealViewController.h"
#interface MainViewController ()
#property (nonatomic) NSMutableArray *plans;
#property (nonatomic) NSArray *categories;
#end
#implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
// [UITableView setDelegate:self];
// [UITableView setDataSource:self];
self.plans = #[#{#"name" : #"Week 1-3", #"category" : #"Buff Dudes Workout"}, #{#"name" : #"Week 4-6", #"category" : #"Buff Dudes Workout"}, #{#"name" : #"Week 7-9", #"category" : #"Buff Dudes Workout"}, #{#"name" : #"Week 10-12", #"category" : #"Buff Dudes Workout"}].mutableCopy;
self.categories = #[#"Buff Dudes Workout"];
self.title = #"Workout Programs";
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.sidebarButton setTarget: self.revealViewController];
[self.sidebarButton setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - DataSource helper methods
- (NSArray *) itemsInCategory:(NSString *)targetCategory {
NSPredicate *matchingPredicate = [NSPredicate predicateWithFormat:#"category == %#", targetCategory];
NSArray *categoryItems = [self.plans filteredArrayUsingPredicate:matchingPredicate];
return categoryItems;
}
- (NSInteger)numberOfItemsInCategory:(NSString *)targetCategory {
return [self itemsInCategory:targetCategory].count;
}
- (NSDictionary *)itemAtIndexPath:(NSIndexPath *)indexPath {
NSString *category = self.categories[indexPath.section];
NSArray *categoryItems = [self itemsInCategory:category];
NSDictionary *item = categoryItems[indexPath.row];
return item;
}
- (NSInteger)itemIndexForIndexPath:(NSIndexPath *)indexPath {
NSDictionary *item = [self itemAtIndexPath:indexPath];
NSInteger index = [self.plans indexOfObjectIdenticalTo:item];
return index;
}
//- (void)removeitemsAtindexPath:(NSIndexPath *)indexPath {
// NSInteger index = [self itemIndexForIndexPath:indexPath];
// [self.items removeObjectAtIndex:index];
#pragma mark - table view datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return self.categories.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self numberOfItemsInCategory:self.categories[section]];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"workoutplanrow";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *plans = [self itemAtIndexPath:indexPath];
cell.textLabel.text = plans[#"name"];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return self.categories[section];
}
#end
I think there is something wrong in my ellForRowAtIndexPath method.
Make sure your tableView dataSource and delegate in IB are connected to files owner (MainViewController).
Add a reference to your tableView and call tableView.reloadData() after setting plans and categories.
updated my .h and .m files. As mentioned i have to get the data (plist
file) from the ViewController1 tableview once rows (multiple) have
been selected to the tableview in the second view controller. Here i struggle mostly since days :)
#import "ViewController1.h"
#interface UIViewController () <UITableViewDataSource, UITableViewDelegate> #end
#implementation ViewController1 {
NSArray *tableData; }
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"TableData" ofType:#"plist"];
NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dictionary objectForKey:#"Cupcakes"];}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated. }
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count]; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
#end
import "ViewController.h"
#import "SWRevealViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize count;
#synthesize countLabel;
#synthesize negative;
- (void)viewDidLoad
{
negative = TRUE;
[super viewDidLoad];
_barButton.target = self.revealViewController;
_barButton.action = #selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
#pragma mark - TableView Deletage and Datasouce methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
}
}
- (IBAction)plus:(UIButton*)sender{
count++;
[self displayCount];
}
- (IBAction)minus:(UIButton*)sender {
count--;
if (negative){ //This simply checks if negative mode is offsw_rear
if (count < 0){ //and if count is negative
count = 0; //sets it back to zero
}}
[self displayCount];
}
- (void)displayCount {
[self.countLabel setText:[[NSString alloc]initWithFormat:#"%ld", (long)self.count]];
}
- (UIViewAnimationOptions) closeAnimationCurve {
return UIViewAnimationOptionCurveEaseOut;
}
// Enabling Deepnes on left menu
- (BOOL)deepnessForLeftMenu
{
return YES;
}
// Enabling Deepnes on left menu
- (BOOL)deepnessForRightMenu
{
return YES;
}
// Enabling darkness while left menu is opening
- (CGFloat)maxDarknessWhileLeftMenu
{
return 0.50;
}
// Enabling darkness while right menu is opening
- (CGFloat)maxDarknessWhileRightMenu
{
return 0.5;
}
#end
Suppose, you have made multiple selections in your main Table.
Then using [mainTable indexPathsForSelectedRows]; will give the indexPaths of the selected cells.
Before you go to next View Controller, pass a array containing selected cells using :
1.) Create a new array in which you loop through these indexPath.row and get the elements from cupcakes Array.
NSMutableArray *selectedCellArray = [[NSMutableArray alloc] init];
for(NSIndexPath *index in [mainTable indexPathsForSelectedRows])
{
[selectedCellArray addObject: cupcakes[index.row]];
}
2.) Pass this to your next View Controller by creating a array property in it.
viewController.tableArray = selectedCellArray;
I am learning to use Search Bars a Search Display Controllers in iOS. I made a simple test project with two views, one view contains a UITableView and a UISearchBar, when you select an row from the table view, the new view shows a label with the name of the row. I'm getting a couple of problems, first when I start to add text in the search bar and the search display appears, the search bar is gone. The filtered results are shown, but when I select a row it does not take me to the next view, this only happens when the table is filtered. Here is the code:
ViewController.h
#import <UIKit/UIKit.h>
#import "DetailViewController.h"
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UISearchDisplayDelegate, UISearchBarDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) IBOutlet UITableView *tableView;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) NSArray *objects;
#property (nonatomic, strong) NSArray *filteredObjects;
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_objects = [[NSMutableArray alloc] initWithObjects:#"One", #"Two", #"Three", #"Four", #"Five", #"Six", #"Seven", #"Eight", #"Nine", #"Ten", nil];
_tableView.delegate = self;
_tableView.dataSource = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [_filteredObjects count];
} else {
return [_objects count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [_filteredObjects objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"ToDetail"]) {
DetailViewController *detailViewController = [segue destinationViewController];
if (self.searchDisplayController.active) {
NSIndexPath *indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
detailViewController.detailString = [_filteredObjects objectAtIndex:indexPath.row];
} else {
NSIndexPath *indexPath = [_tableView indexPathForSelectedRow];
detailViewController.detailString = [_objects objectAtIndex:indexPath.row];
}
}
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#", searchText];
_filteredObjects = [_objects filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
Thanks for the help!
when I select a row it does not take me to the next view, this only happens when the table is filtered
Because you have no implementation of tableView:didSelectRowAtIndexPath:.
Remember, there is really no such thing as a "filtered table view". There are two table views: the normal one, and the one that appears because of the search display controller. That is a different table view (basically appearing in front of yours), and you must configure it for whatever you want it to do and however you want it to look.
I am trying to gain some knowledge on UISearchDisplayController and going through some tutorial with examples, I have the below class ready with a search bar and table view with data on it.
Header file:
#import <UIKit/UIKit.h>
#interface MyClass : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchDisplayDelegate, UISearchBarDelegate>
#property (nonatomic, strong) IBOutlet UITableView *suggestionsTableView;
#property (nonatomic, strong) IBOutlet UISearchBar *searchBar;
#end
Implementation file:
#import "MyClass.h"
#interface DVWNoteTypeSuggestionDisplayController ()
#property (nonatomic, strong) NSArray *items;
#property (nonatomic)BOOL isSearching;
#property (nonatomic, strong) NSMutableArray *filteredList;
#end
#implementation MyClass
- (id)init
{
self = [super initWithNibName:#"SuggestionDisplayController" bundle:BUNDLE];
if (self)
{
// Set the title.
self.title = #"test";
}
return self;
}
- (void)viewDidLoad
{
self.searchBar = [[UISearchBar alloc] init];
[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.delegate = self;
self.searchBar.frame = CGRectMake(0, 0, 0, 38);
self.suggestionsTableView.tableHeaderView = self.searchBar;
self.items = [[NSArray alloc] initWithObjects:#"Item No. 1", #"Item No. 2", #"Item No. 3", #"Item No. 4", #"Item No. 5", #"Item No. 6", nil];
self.isSearching = NO;
self.filteredList = [[NSMutableArray alloc] init];
}
#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.
// // Usually the number of items in your array (the one that holds your list)
// return [self.items count];
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (self.isSearching)
{
//If the user is searching, use the list in our filteredList array.
return [self.filteredList count];
} else
{
return [self.items count];
}
}
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// //Where we configure the cell in each row
//
// static NSString *CellIdentifier = #"Cell";
// UITableViewCell *cell;
//
// cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// if (cell == nil) {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
// // Configure the cell... setting the text of our cell's label
// cell.textLabel.text = [self.items objectAtIndex:indexPath.row];
// return cell;
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSString *title;
if (self.isSearching && [self.filteredList count]) {
//If the user is searching, use the list in our filteredList array.
title = [self.filteredList objectAtIndex:indexPath.row];
} else
{
title = [self.items objectAtIndex:indexPath.row];
}
cell.textLabel.text = title;
return cell;
}
- (void)filterListForSearchText:(NSString *)searchText
{
[self.filteredList removeAllObjects]; //clears the array from all the string objects it might contain from the previous searches
for (NSString *title in self.items) {
NSRange nameRange = [title rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (nameRange.location != NSNotFound) {
[self.filteredList addObject:title];
}
}
}
#pragma mark - UISearchDisplayControllerDelegate
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
//When the user taps the search bar, this means that the controller will begin searching.
self.isSearching = YES;
}
- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller {
//When the user taps the Cancel Button, or anywhere aside from the view.
self.isSearching = NO;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterListForSearchText:searchString]; // The method we made in step 7
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterListForSearchText:[self.searchDisplayController.searchBar text]]; // The method we made in step 7
// Return YES to cause the search result table view to be reloaded.
return YES;
}
#end
Whenever I try to search for any items in the data set (eg: "Item No. 5") its not hitting the breakpoints on any of the delegate i.e. actually the search is not working. Please suggest what am I missing here as this is just my learning project right now.
It appears that a UISearchDisplayController created programatically in this way is prematurely zeroing the delegate, even though the view controller is retaining the UISearchDisplayController as expected.
Add the following to the end of your viewDidLoad and you'll see that the first log will be a valid object, but the second will be null.
NSLog(#"Delegate should be %#", self.searchDisplayController.delegate);
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
NSLog(#"Delegate is %#", self.searchDisplayController.delegate);
});
The quickest way I've found to get around this is to store your own reference to the UISearchDisplayController via a private property or ivar.
If you have to create object for search bar controller and set delegate search bar its work.
UISearchBar *searchBar = [[UISearchBar alloc] init];
[[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchDisplayController.searchResultsDelegate = self;
self.searchDisplayController.searchResultsDataSource = self;
self.searchDisplayController.delegate = self;
searchBar.frame = CGRectMake(0, 0, 0, 38);
self.tableView.tableHeaderView = searchBar;