how to push tableview to UIView dynamically in iOS? - ios

i am displaying list content in table view now i want when i click
one menu of list that menu content display in UIView on next screen
. how to push UITableView to UIView dynamically in iOS.
#import "SmsCategoryTitleTableViewController.h"
#import "CategoryMainWindowViewController.h"
#import "AppDelegate.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "SmsTitle.h"
#import "SMSCategory.h"
#import"smsDisplayViewController.h"
#interface SmsCategoryTitleTableViewController ()
#end
#implementation SmsCategoryTitleTableViewController
#synthesize theSearchBar,Id;
#synthesize theTableView;
#synthesize array;
#synthesize disableViewOverlay;
#synthesize Arrayobject;
- (void)viewDidLoad
{
[super viewDidLoad];
[self SearchBarCode];
[self GetTableData];
[self.tableView reloadData];
filteredContentList = [[NSMutableArray alloc] init];
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self
action:#selector(dismissKeyboard)];
[self.view addGestureRecognizer:tap];
// [self performSelector:#selector(push:) withObject:nil afterDelay:0.2f];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
-(void)GetTableData
{
array = [[NSMutableArray alloc] init];
NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentDir = [docPaths objectAtIndex:0];
self.databasePath = [documentDir stringByAppendingPathComponent:#"SMS.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:self.databasePath];
[database setLogsErrors:TRUE];
[database open];
NSString *anQuery = [[NSString alloc]initWithFormat:#"SELECT * FROM SMSnJokes
where CategoryId=%#",self.Id];
FMResultSet *results = [database executeQuery:anQuery];
while([results next])
{
SmsTitle *title=[[SmsTitle alloc]init];
title.Id = [results stringForColumn:#"Id"];
title.CategoryId = [results stringForColumn:#"CategoryId"];
title.Title = [results stringForColumn:#"Title"];
[array addObject:title];
// NSLog(#"SMS LIST %#",title.Title);
}
[database close];
}
-(void)SearchBarCode
{
self.disableViewOverlay = [[UIView
alloc]initWithFrame:CGRectMake(0.0f,44.0f,320.0f,0)];
self.disableViewOverlay.backgroundColor=[UIColor lightGrayColor];
self.disableViewOverlay.alpha = 0;
theSearchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 5, 374.0f, 50)];
theSearchBar.delegate =self;
[self.tableView addSubview:theSearchBar];
self.navigationItem.title=#"SMS LIST";
[[self tableView] setTableHeaderView:theSearchBar];
}
- (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 (isSearching)
{
return [filteredContentList count];
}
else
{
return [array 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 (isSearching)
{
cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
}
else
{
SmsTitle *title = [array objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:#"%# ",[title
valueForKey:#"Title"]]];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)searchTableList
{
NSString *searchString =theSearchBar.text;
filteredContentList = [[NSMutableArray alloc]init];
[filteredContentList removeAllObjects];
for (SmsTitle *title in array)
{
NSString *tempStr = title.Title;
NSComparisonResult result = [tempStr compare:searchString options:
(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0,
[searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:title.Title];
}
}
}
#pragma mark - Search Implementation
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self.theSearchBar resignFirstResponder];
}
- (void) dismissKeyboard
{
[self.theSearchBar becomeFirstResponder];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearching = YES;
[theSearchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
}
else {
isSearching = NO;
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
theSearchBar.text=nil;
[theSearchBar setShowsCancelButton:NO animated:YES];
[theSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[theSearchBar setShowsCancelButton: YES animated: YES];
[self searchTableList];
[searchBar resignFirstResponder];
}
- (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];
NSIndexPath *selected = [self.theTableView indexPathForSelectedRow];
if (selected)
{
[self.theTableView deselectRowAtIndexPath:selected
animated:NO];
}
}
[searchBar setShowsCancelButton:active animated:YES];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
[self.theSearchBar resignFirstResponder];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
textField.returnKeyType=UIReturnKeyDefault ;
return[textField resignFirstResponder];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath
*)indexPath
{
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc]
init];
[self.navigationController pushViewController:viewController1 animated:YES];
}

Ok got your point. I think you want to pass data of selected cell to
next UIViewController. Assume, you want to pass cell title label and
you have an array of objects. In yoursmsDisplayViewController.h
#import <UIKit/UIKit.h>
#interface smsDisplayViewController : UIViewController
#property (strong, nonatomic) NSString *cellName;
Now in your SmsCategoryTitleTableViewController.m you have
NSMutableArray *nameList;
Then in your table view delegate method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [self.storyboard instantiateViewControllerWithIdentifier:#"LoginIdentifier"];
viewController1.cellName=[nameList objectAtIndex:indexPath.row];
[self.navigationController pushViewController:viewController1 animated:YES];
}
UPDATE This is the code you posted first in your question.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
smsDisplayViewController *viewController1 = [[smsDisplayViewController
alloc] initWithNibName:#"viewController1" bundle:nil];
[self.navigationController pushViewController:viewController1 animated:YES];
}
Now the wrong thing you are doing here
isinitWithNibName:#"viewController1". If you are not using any nib
file then your code should be
smsDisplayViewController *viewController1 = [[smsDisplayViewController alloc] init];
[self.navigationController pushViewController:viewController1 animated:YES];

You can use Accessory Buttons in UITableView or learn more about segues.

You have to use prepareForSegue: to pass data to another ViewController.
You can learn it from Here which teaches you how to transfer data between ViewControllers while using Segue.

Related

How to make textfield input view as search bar?

I have tried to get proper solution ,but I can't any programmers please give me a idea how to make.
1.is it possible to make uitextfield as uisearchbar?
UISearchBar *search=[[UISearchBar alloc]init];
search.delegate=self;
[_txtLocation setInputView:search];
2.While user types the values I need show it as overlay at the bottom of the text field...
3.Please help me to find out the solution..
To make Text Field work like Search Bar implement - (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string delegate method of UITextField. So basically, you need to implement AutoComplete feature and this how you do it.
To detect which textfield is triggered use assign tag to the textfield.
In your ViewController.h file:
#interface ViewController :
<UIViewController<UITextFieldDelegate,UITableViewDataSource, UITableViewDelegate>
{
UITableView *autocompleteTableView;
UITextField * searchtextField1;
UITextField * searchtextField2;
NSMutableArray *autoCompleteList;
NSMutableArray *initalList;
}
In your ViewController.m file:
- (void)viewDidLoad {
searchtextField1 = [[UITextField alloc]
initWithFrame:CGRectMake(5,0, 245, 33)];
searchtextField2.tag = 2;
searchtextFeild1.tag = 1;
searchtextField.placeholder = #"eg: make up";
searchtextField.textColor = [UIColor whiteColor];
//[imageView addSubview:searchtextField];
//[self.view addSubview:imageView];
autoCompleteList = [[NSMutableArray alloc] init];
searchtextField1.delegate = self;
searchtextField2.delegate = self;
autocompleteTableView = [[UITableView alloc]init];
if(screenRect.size.height == 568)
{
float X_Co_tbl = (self.view.frame.size.width - 271)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 105, 271, 120)];
}
else if (screenRect.size.width == 414)
{
float X_Co_tbl = (self.view.frame.size.width - 281)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 145, 281, 120)];
}
else if(screenRect.size.width == 375)
{
float X_Co_tbl = (self.view.frame.size.width - 281)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 125, 281, 120)];
}
else
{
float X_Co_tbl = (self.view.frame.size.width - 271)/2;
[autocompleteTableView setFrame:CGRectMake(X_Co_tbl, 95, 271, 120)];
}
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
autocompleteTableView.hidden = YES;
return YES;
}
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
autocompleteTableView.hidden = NO;
if (textField.tag == 1) {
/// Initialize your array for searchTextFeild1;
initialList = [[NSMutableArray alloc]initWithObjects:#"Face wash",#"Morning face wash",#"Cleanser", nil];
}
if (textField.tag == 2) {
/// Initialize your array for searchTextFeild2;
initialList = [[NSMutableArray alloc]initWithObjects:#"Face wash",#"Morning face wash",#"Cleanser", nil];
}
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring
stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
/// You make Text Field work as Search Bar here
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autoCompleteList removeAllObjects];
for(NSString *curString in initialList) {
//NSRange substringRange = [curString rangeOfString:substring];
if ([curString rangeOfString:substring options:NSCaseInsensitiveSearch].location != NSNotFound) {
[autoCompleteList addObject:curString];
}
}
[autocompleteTableView reloadData];
}
#pragma mark UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
return autoCompleteList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}
cell.textLabel.text = [autoCompleteList objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
searchtextField.text = selectedCell.textLabel.text;
autocompleteTableView.hidden = YES;
[self goPressed];
}
In .h file
#import <UIKit/UIKit.h>
#interface SEMainVC : UIViewController <UITextFieldDelegate>{
NSMutableArray *dummyArray;
NSMutableArray *searchArray;
NSString *searchTextString;
}
#property (weak, nonatomic) IBOutlet UITextField *searchTextField;
#property (weak, nonatomic) IBOutlet UITableView *contentTableView;
- (void) setupData;
#end
In .m file
#interface SEMainVC ()
#end
#implementation SEMainVC
- (void)viewDidLoad
{
[super viewDidLoad];
//set the selector to the text field in order to change its value when edited
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//here you set up the methods to search array and reloading the tableview
[self setupData];
[self updateSearchArray];
[self.contentTableView reloadData];
}
//setting up the data sourch for the mutable array
- (void) setupData {
dummyArray = [[NSMutableArray alloc] init];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 1", #"name" , #"image1.JPG", #"image" , #"dummy 1 description textview", #"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 2", #"name" , #"image1.JPG", #"image" , #"dummy 2 description textview", #"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 3", #"name" , #"image1.JPG", #"image" , #"dummy 3 description textview", #"description", nil]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [searchArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if( cell == nil ){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.textLabel.text = [[searchArray objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self performSegueWithIdentifier:#"DummyDetail" sender:[NSNumber numberWithInt:indexPath.row]];
}
#pragma mark - Search Methods
-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray];
}
//update seach method where the textfield acts as seach bar
-(void)updateSearchArray
{
if (searchTextString.length != 0) {
searchArray = [NSMutableArray array];
for ( NSDictionary* item in dummyArray ) {
if ([[[item objectForKey:#"name"] lowercaseString] rangeOfString:[searchTextString lowercaseString]].location != NSNotFound) {
[searchArray addObject:item];
}
}
} else {
searchArray = dummyArray;
}
[self.contentTableView reloadData];
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(NSNumber*)indexNumber
{
if([[segue identifier] isEqualToString:#"DummyDetail"]){
NSInteger index = [indexNumber integerValue];
SEDetailVC *dummyDetail = [segue destinationViewController];
dummyDetail.dummyImageString = [[searchArray objectAtIndex:index] objectForKey:#"image"];
dummyDetail.dummyTextString = [[searchArray objectAtIndex:index] objectForKey:#"description"];
dummyDetail.title = [[searchArray objectAtIndex:index] objectForKey:#"name"];
}
}
- (void)viewDidUnload {
[self setSearchTextField:nil];
[self setContentTableView:nil];
[super viewDidUnload];
}
#end

UISearchBar search not clearing old cells

I'm trying to implement a UISearchBar in a custom UITableViewController and done programmatically (not using IB). I got the search function to work and return the correct fields, but it is displaying the searched cells over the full list cells:
As you can see, the new searched field is scrollable and selectable. Its just not removing the old cells.
here is my .h file:
#interface TestTableViewController : UITableViewController <UISearchBarDelegate, UISearchDisplayDelegate>
#property (strong, nonatomic) NSArray *boundaries;
#end
.m file:
#import "TestTableViewController.h"
#import "Boundary.h"
#interface TestTableViewController ()
#property (strong, nonatomic) UISearchDisplayController *searchController;
#property (strong, nonatomic) NSMutableArray *filteredBoundaries;
#end
#implementation TestTableViewController
-(instancetype) initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) {
self.filteredBoundaries = [NSMutableArray array];
}
return self;
}
-(void)viewDidLoad {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:TRUE selector:#selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = #[sortDescriptor];
self.boundaries = [self.boundaries sortedArrayUsingDescriptors:sortDescriptors];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.delegate = self;
searchBar.placeholder = #"Search Fields";
searchBar.showsCancelButton = TRUE;
self.tableView.tableHeaderView = searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Setup Filter Data Source
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
[self.filteredBoundaries removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name contains[c] %#", searchText];
self.filteredBoundaries = [NSMutableArray arrayWithArray:[self.boundaries filteredArrayUsingPredicate:predicate]];
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.filteredBoundaries.count;
}
else {
return self.boundaries.count;
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
Boundary *boundary = [self.filteredBoundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
else {
Boundary *boundary = [self.boundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.userInteractionEnabled = TRUE;
}
return cell;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark UISearchDisplayController Delegates
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchController.searchBar scopeButtonTitles] objectAtIndex:self.searchController.searchBar.selectedScopeButtonIndex]];
return TRUE;
}
#end
And how I call the table view:
TestTableViewController *tableViewController = [[TestTableViewController alloc] initWithStyle:UITableViewStylePlain];
tableViewController.boundaries = [group.boundaries allObjects];
tableViewController.contentSizeForViewInPopover = POPOVER_SIZE;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tableViewController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.navigationBar.barStyle = UIBarStyleBlack;
self.myPopoverController = [[UIPopoverController alloc] initWithContentViewController:navController];
self.myPopoverController.delegate = self;
[self.myPopoverController presentPopoverFromRect:button.frame inView:button.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Any ideas what I might be doing wrong or missing?
The problem is that UISearchDisplayController is using another UITableView rather than the view controller's own. You can verify that by logging tableView in -tableView:cellForRowAtIndexPath:.
You can use a UISearchBar without a UISearchDisplayController, to have more control over search and display logic.
Also, if your app doesn't support any version prior to iOS 8, consider using UISearchController. I haven't tried it but it seems to give you more control. Check a sample UISearchDisplayControllerhas been deprecated in iOS 8.
Try this
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 41.0)];
[self.view addSubview:searchBar];
searchBar.delegate=self;
- (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 (isSearching) {
return [filteredContentList count];
}
else {
return [titlearray count];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (isSearching)
{
cell.nameLabel.text = [filteredContentList objectAtIndex:indexPath.row];
cell.thumbnailImageView.image =[filteredImgArray objectAtIndex:indexPath.row];
}
else
{
cell.thumbnailImageView.image = [imagearray objectAtIndex:indexPath.row];
cell.nameLabel.text = [titlearray objectAtIndex:indexPath.row];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = searchBar.text;
for (int i=0; i<titlearray.count; i++) {
NSString *tempStr=[titlearray objectAtIndex:i];
NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:tempStr];
[filteredImgArray addObject:[imagearray objectAtIndex:i]];
}
}
}
#pragma mark - Search Implementation
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
[filteredImgArray removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
//tblContentList.hidden=NO;
}
else {
isSearching = NO;
// tblContentList.hidden=YES;
}
[tblContentList reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
I hope it's help for you
You should implement correct datasource.
Create new array of items for filtered data for first.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = ([filteredItems count] > 0) ? [filteredItems count] : [self.allItems count];
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier: #"id"];
MyCustomItem *item = ([filteredItems count] > 0) ? filteredItems[indexPath.row] : self.allItems[indexPath.row];
[self configureCell:cell forItem:item];
return cell;
}
Configure searching:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchText = searchController.searchBar.text;
if ([searchText length] == 0)
{
[filteredItems removeAllObjects];
[self.tableView reloadData];
return;
}
NSMutableArray *searchResults = [self.allItems mutableCopy];
// SKIP ALL BODY OF SEARCHING
filteredPeoples = searchResults;
[self.tableView reloadData];
}
Will work pretty.
IOS 8 delegate has been deprecated not sure if that's the problem.
The method
here's [a link]https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UISearchDisplayDelegate_Protocol/index.html#//apple_ref/occ/intfm/UISearchDisplayDelegate/searchDisplayControS 8 delegate has been deprecated not sure if that's the problem.
The method
try this property instead
#property(nonatomic, assign) id< UISearchResultsUpdating > searchResultsUpdater
another better link [a link]https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Listings/TableSearch_obj_c_TableSearch_APLResultsTableController_m.html

How to keep text in search bar when dismiss UISearchDisplayController

I'm using a UISearchDisplayController in my app. When the user selects an item in the search results returned I deactivate the UISearchDisplayController. Deactivating the controller clears the text the user has typed. I want to keep it there. I try to assign the text back into the UISearchBar by setting it again after the controller has been deactivated. The text does appear in the search bar but this will cause the UISearchDisplayController to active again even though I have disable the delegate! This issue only happens on iOS 7. Before iOS7, the code below works charmingly.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSUInteger row = [indexPath row];
NSString *term = [keywordSuggestion objectAtIndex:row];
[search resignFirstResponder];
[self handleSearchForTerm:term];
}
-(void)handleSearchForTerm:(NSString *)searchTerm {
[searchDisplayController setActive:NO animated:YES]; //searchbar text will be lost
searchDisplayController.delegate = nil;
search.text = term;
searchDisplayController.delegate = self;
}
Is there are a way that I can set the text of the UISearchBar without having the UISearchDisplayController that's associated with become active?
Here is an example of some working code:
#import "RBTableViewController.h"
#interface RBTableViewController () <UISearchDisplayDelegate>
#end
#implementation RBTableViewController {
UISearchBar *_searchBar;
UISearchDisplayController *_searchController;
NSMutableArray *_searchResults;
NSMutableArray *_model;
NSString *_cachedSearchTerm;
}
- (NSMutableArray *)currentModel {
return _searchController.isActive ? _searchResults : _model;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_searchResults = [[NSMutableArray alloc] init];
_model = [[NSMutableArray alloc] init];
for (int i = 0; i < 10; i++) {
[_model addObject:[NSString stringWithFormat:#"item %d", i]];
}
_searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
_searchController = [[UISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
_searchController.searchResultsDataSource = self;
_searchController.searchResultsDelegate = self;
_searchController.delegate = self;
[_searchController.searchResultsTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
self.tableView.tableHeaderView = _searchBar;
}
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller {
controller.searchBar.text = _cachedSearchTerm;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == _searchController.searchResultsTableView) {
_cachedSearchTerm = _searchBar.text;
[_searchController setActive:NO animated:YES];
[self filterResults:_cachedSearchTerm];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [[self currentModel] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.text = [self currentModel][indexPath.row];
return cell;
}
- (void)filterResults:(NSString *)searchTerm {
[_searchResults removeAllObjects];
[_searchResults addObjectsFromArray:[_model filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"SELF contains[s] %#", searchTerm]]];
[_searchController.searchResultsTableView reloadData];
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterResults:searchString];
return YES;
}
- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)controller {
if (_cachedSearchTerm) {
controller.searchBar.text = _cachedSearchTerm;
}
}
#end

uisearchdisaplycontroller inside uiviewcontrolelr - programmatically

I create a UIViewController with a UITableView and UISearchDisplayController, the problem is that shouldReloadTableForSearchString not run...this is my code, where is the mistake for you?
- (void)viewDidLoad {
[super viewDidLoad];
array = [[NSMutableArray alloc] initWithObjects:#"ciao",#"mandi",#"viva",#"blabla", nil];
arrayFiltrato = [[NSMutableArray alloc] initWithObjects:#"ciao",#"mandi",#"viva",#"blabla", nil];
//[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:NO];
[self.tableView reloadData];
[self setSearchBar];
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];
[self.navigationController setNavigationBarHidden: NO];
}
- (void) setSearchBar {
self.searchBar = [[UISearchBar alloc] init];
[self.searchBar setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[self.searchBar setPlaceholder:#"Type a search term" ];
[self.searchBar setTintColor:[UIColor blackColor]];
[self.searchBar setDelegate:self];
[self.searchBar sizeToFit];
[self.tableView setTableHeaderView:self.searchBar];
self.searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
[self.searchDisplay setSearchResultsDataSource:self];
[self.searchDisplay setSearchResultsDelegate:self];
[self.searchDisplay setDelegate:self];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)myTableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)myTableView numberOfRowsInSection:(NSInteger)section {
if (myTableView == self.tableView) {
return array.count;
}
else{
return arrayFiltrato.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)myTableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (myTableView == self.tableView) {
cell.textLabel.text = [array objectAtIndex:indexPath.row];
} else {
cell.textLabel.text = [arrayFiltrato objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark -
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
[arrayFiltrato removeAllObjects];
// if ([scope isEqualToString:#"All"] || [product.type isEqualToString:scope]) {
for (NSString *str in array) {
NSLog(#"str: %# - scope: %#",str,scope);
if ([scope isEqualToString:str]) {
NSComparisonResult result = [str compare:searchText
options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame) {
[arrayFiltrato addObject:str];
}
}
}
}
#pragma mark -
#pragma mark UIsearchDisplay Delegate Methods
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
NSLog(#"ok");
return YES;
}
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption{
NSLog(#"ok");
[self filterContentForSearchText:[self.searchDisplayController.searchBar text]
scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
- (void)searchDisplayDidBeginSearch:(UISearchDisplayController *)controller{
[self.searchDisplayController.searchResultsTableView setDelegate:self];
}
- (void)searchDisplayDidEndSearch:(UISearchDisplayController *)controller{
//[self.tableView setContentOffset:CGPointMake(0, 44.f) animated:YES];
}
#pragma mark -
-(void)searchBar:(id)sender{
[self.searchDisplayController setActive:YES animated:YES];
}
The problem is that the delegate method is wrong, isn't this:
- (BOOL)searchDisplay:(UISearchDisplayController *)controller shouldRelo....
but this:
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldRelo...

Updating of a Mutable Array

I have a mutable Array in a Tableview, this is populated on View did load from an SQLite database, However this database changes as it is a favourites database for products in my app.
When a user selects one of the items in the tableview (The user then goes to a detail view, with the info from the database) the user can then select to remove it from the favourites (database) when the user then presses back in the navigation bar, the item is still there, I've tried tableview reload on view did appear, and view will appear but that doesn't help,
Can anyone shed any light on this??
Many thanks,
Andrew
Here is my code:
FavTableViewController.h:
#interface FavTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *Table;
}
#property (nonatomic, strong) UITableView *Table;
#property (nonatomic, strong) NSArray *cats;
#property (nonatomic, strong) IBOutlet UISearchBar *searchBar;
#property (nonatomic, strong) UISearchDisplayController *searchDisplayController;
#property (nonatomic, strong) NSMutableArray *filteredListContent;
#property (nonatomic, strong) NSMutableArray *listContent;
#property (nonatomic, strong) NSArray *everything;
#property (nonatomic, copy) NSString *savedSearchTerm;
#property (nonatomic) NSInteger savedScopeButtonIndex;
#property (nonatomic) BOOL searchWasActive;
#property (nonatomic, strong) NSString *cellText;
-(void) refresh;
#end
FavTableViewController.m:
#import "FavTableViewController.h"
#import "DBFavAdapter.h"
#import "MenuData.h"
#import "DBAdapter.h"
#import "DetailViewController.h"
#import "ConsoleDetailController.h"
#import "EffectDetailViewController.h"
#import "DimmersDetailController.h"
#import "ConventionalController.h"
#import "ProDetailViewController.h"
#implementation FavTableViewController
#synthesize filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive, searchBar, searchDisplayController, listContent, everything, cellText, cats, Table;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
listContent = [[NSMutableArray alloc] init];
}
return self;
}
- (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.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
NSLog(#"Did Load");
[super viewDidLoad];
everything = [[DBFavAdapter allProducts] mutableCopy];
for (NSDictionary *dict in everything) {
[listContent addObject: [dict objectForKey:#"Title"]];
}
// create a filtered list that will contain products for the search results table.
self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];
// restore search settings if they were saved in didReceiveMemoryWarning.
if (self.savedSearchTerm)
{
[self.searchDisplayController setActive:self.searchWasActive];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
[self.searchDisplayController.searchBar setText:savedSearchTerm];
self.savedSearchTerm = nil;
}
// [self.tableView reloadData];
self.Table.scrollEnabled = YES;
self.navigationItem.title = #"Favourites";
// cats = [DBFavAdapter allCategories];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.filteredListContent = nil;
NSLog(#"Unload");
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"View will Appear");
[Table reloadData];
NSLog(#"Everything: %#",everything);
NSLog(#"list Content: %#",listContent);
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"View did Appear");
[super viewDidAppear:animated];
NSLog(#"list Content appeared: %#",listContent);
[Table reloadData];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
NSLog(#"Did dissapear");
// save the state of the search UI so that it can be restored if the view is re-created
self.searchWasActive = [self.searchDisplayController isActive];
self.savedSearchTerm = [self.searchDisplayController.searchBar text];
self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView == self.searchDisplayController.searchResultsTableView){
return [self.filteredListContent count];
}
else {
return [self.listContent count];
}
NSLog(#"Rows %i",[self.listContent count]);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
if (tableView == searchDisplayController.searchResultsTableView)
{
cellText = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
cellText = [self.listContent objectAtIndex:indexPath.row];
}
// NSString *cellText = [self.listContent objectAtIndex:indexPath.row];
UIFont *cellFont = [UIFont fontWithName:#"Heiti TC" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 30;
}
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = 1;
return row;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Heiti TC" size:17.0];
}
// Configure the cell...
if (tableView == searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [self.listContent objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedItem;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
selectedItem = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
selectedItem = [self.listContent objectAtIndex:indexPath.row];
}
// Is the selection a category?
// NSArray *cats = [DBAdapter allCategories];
__block BOOL cat = NO;
[cats enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([(NSString*)obj isEqualToString:selectedItem]) {
cat = YES;
*stop = YES;
}
}];
if (cat) { // the user's selection was a category
// NSLog(#"Selected item was a category");
}
else {
NSArray *mans = [DBAdapter allManufacturers];
__block BOOL man = NO;
[mans enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([(NSString*)obj isEqualToString:selectedItem]) {
man = YES;
*stop = YES;
}
}];
if (man) { // the user's selection was a manufacturer
// NSLog(#"Selected item was a manufacturer");
} else {
// the user's selection was a product
// Find selectedItem in products
__block NSDictionary *selectedRow = nil;
[self.everything enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
//everything is an array of dictionaries
if ([(NSString*)[(NSDictionary*)obj objectForKey:#"Title"] isEqualToString:selectedItem]) {
selectedRow = (NSDictionary*)obj;
*stop = YES;
}
}];
MenuData *selectionData = [MenuData menuData];
selectionData.manufacturerID = [[selectedRow objectForKey:#"Manufacturer_id"] integerValue];
selectionData.categoryID = [[selectedRow objectForKey:#"Category_id"] integerValue];
selectionData.sCategoryID = [[selectedRow objectForKey:#"SubCategory_id"] integerValue];
selectionData.ssCategoryID = [[selectedRow objectForKey:#"SuperSubCategory_id"] integerValue];
NSString *selectedTitle = [selectedRow objectForKey: #"Title"]; // You probably already have this value from your search. Here for the sake of clarity.
NSDictionary *productDetails = [DBAdapter productDetails: selectedTitle forCurrentData: selectionData];
NSArray *allKeys = [productDetails allKeys];
// NSLog(#"values: %i", [allKeys count]);
for (NSString *key in allKeys) {
id value = [productDetails objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
// NSLog(#"key: %# value: %#", key, value);
}
}
NSInteger ViewNumber = [[productDetails objectForKey:#"View"] integerValue];
switch (ViewNumber) {
case 25: {
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:[NSBundle mainBundle]];
dvController.dictionary = productDetails;
[self.navigationController pushViewController:dvController animated:YES];
}
break;
case 18: {
EffectDetailViewController *edvController = [[EffectDetailViewController alloc] initWithNibName:#"EffectDetailView" bundle:[NSBundle mainBundle]];
edvController.dictionary = productDetails;
[self.navigationController pushViewController:edvController animated:YES];
}
break;
case 17: {
ConsoleDetailController *cdvController = [[ConsoleDetailController alloc] initWithNibName:#"ConsoleDetailController" bundle:[NSBundle mainBundle]];
cdvController.dictionary = productDetails;
[self.navigationController pushViewController:cdvController animated:YES];
}
break;
case 2: {
ConsoleDetailController *cdvController = [[ConsoleDetailController alloc] initWithNibName:#"ConsoleDetailController" bundle:[NSBundle mainBundle]];
cdvController.dictionary = productDetails;
[self.navigationController pushViewController:cdvController animated:YES];
}
break;
case 3: {
DimmersDetailController *ddvController = [[DimmersDetailController alloc] initWithNibName:#"DimmersDetailController" bundle:[NSBundle mainBundle]];
ddvController.dictionary = productDetails;
[self.navigationController pushViewController:ddvController animated:YES];
}
break;
case 12: {
ConventionalController *cController = [[ConventionalController alloc] initWithNibName:#"ConventionalController" bundle:[NSBundle mainBundle]];
cController.dictionary = productDetails;
[self.navigationController pushViewController:cController animated:YES];
}
break;
case 5: {
ProDetailViewController *pController = [[ProDetailViewController alloc] initWithNibName:#"ProDetailViewController" bundle:[NSBundle mainBundle]];
pController.dictionary = productDetails;
[self.navigationController pushViewController:pController animated:YES];
}
break;
}
}
}
}
#pragma mark -
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
for (NSString *product in listContent)
{
//Edit AD - NS Range works instead of NSComparisonResult
NSRange result = [product rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
if (result.location != NSNotFound)
{
[self.filteredListContent addObject:product];
}
/*
// NSComparisonResult result = [product compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:product];
}
*/
}
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)refresh {
NSLog(#"Refresh");
if([NSThread isMainThread])
{
[self.Table reloadData];
[self.Table setNeedsLayout];
[self.Table setNeedsDisplay];
}
else
{
[self performSelectorOnMainThread:#selector(refresh) withObject:nil waitUntilDone:YES];
}
}
#end
You have 2 options.
Remove the item from the listContent as well. This can be done via a delegate method that will be called from the child view controller when you delete the item.
Move your viewDidLoad functionality where listContents is generated from the database to viewWillAppear. This will cause listContents to read the database again, after the item was deleted and you hit the back button, this will also get called when the view first opens.

Resources