Obj-C - didSelectRowAtIndexPath not firing? - ios

I'm stumped. For some reason, when I tap my tableView cell, didSelectRowAtIndexPath is not executing? And yes, my tableView delegate is set, and data is populated in the cell label. Am I missing something obvious from my below? Essentially, when my user taps the tableView cell, the contents of the cell label should appear in a textfield.
.h
#interface RegisterViewController : UIViewController <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate> {
}
#property (nonatomic) IBOutlet UITableView *tableView;
#end
.m
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.hidden = NO;
self.tableView.delegate = self;
self.tableView.dataSource = self;
}
- (void)LoadJson_search{
searchArray=[[NSMutableArray alloc]init];
// NSLog(#"str......%#",strSearch);
// This API key is from https://developers.google.com/maps/web/
NSString *str1 = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyAm7buitimhMgE1dKV2j4_7doULluiiDzU", strSearch];
NSURL *url = [NSURL URLWithString:str1];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error=nil;
if(data.length==0)
{
}
else
{
NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"1,,,,%#",jsondic);
[searchArray removeAllObjects];
if([[jsondic objectForKey:#"status"]isEqualToString:#"ZERO_RESULTS"])
{
}
else if([[jsondic objectForKey:#"status"]isEqualToString:#"INVALID_REQUEST"])
{
}
else
{
for(int i=0;i<[jsondic.allKeys count];i++)
{
NSString *str1=[[[jsondic objectForKey:#"predictions"] objectAtIndex:i] objectForKey:#"description"];
[searchArray addObject:str1];
}
self.tableView.hidden = NO;
// NSLog(#"%#", searchArray);
}
if (searchArray.count == 0) {
self.tableView.hidden = YES;
}else{
[self.tableView reloadData];
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// if (self.addressField.tag == 3) {
if (textField == self.addressField) {
strSearch = [self.addressField.text stringByReplacingCharactersInRange:range withString:string];
if([string isEqualToString:#" "]){
}else{
[self LoadJson_search];
}}
// }
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
self.tableView.hidden = YES;
[self.tableView reloadData];
return YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return searchArray.count;
}
-(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"cell"];
if(!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"TAPPED CELL");
self.addressField.text = [searchArray objectAtIndex:indexPath.row];
self.tableView.hidden = YES;
[self.tableView reloadData];
}

Try with the next line in your viewDidLoad:
self.tableView.allowsSelection = YES;
Or check that property in your storyboard. Well you can try with the cell too like this:
// This line do not affect the selection delegate only the style
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = YES;

Related

How to apply custom search on uitextfield for place search using gmsAutocomplete view controller.?

HI all i am working on GMSAutocompleteViewController in my app. i have a uitextfield in my view controller when i tapp textfield for search a place using google api, a new view is open which is powered by google. Look at my code please.
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
tappedTextField = textField;
GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
acController.delegate = self;
[self presentViewController:acController animated:YES completion:nil];
}
- (void)viewController:(GMSAutocompleteViewController *)viewController
didAutocompleteWithPlace:(GMSPlace *)place {
// Do something with the selected place.
NSLog(#"Place name %#", place.name);
NSLog(#"Place address %#", place.formattedAddress);
NSLog(#"Place attributions %#", place.attributions.string);
NSLog(#"lat and log%f", place.coordinate.latitude);
NSLog(#"lang %f", place.coordinate.longitude);
tappedTextField.text = place.name;
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewController:(GMSAutocompleteViewController *)viewController
didFailAutocompleteWithError:(NSError *)error {
// TODO: handle the error.
NSLog(#"error: %ld", (long)[error code]);
[self dismissViewControllerAnimated:YES completion:nil];
}
// User canceled the operation.
- (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
NSLog(#"Autocomplete was cancelled.");
[self dismissViewControllerAnimated:YES completion:nil];
}
i don't want to move to another view on textfield tapp for searching. is it possible that i can search places from the textfield only?
when i click on destination textfield a new view is appear for searching but i need search from textfield only please at the screen after tapp the textfield.
It sounds like what you're after is to display the autocomplete results in a table immediately underneath the textfield when the text field is active (ie something similar to this).
You can do this by creating a UITableView that you display in your UI in the right location. Instead of using GMSAutocompleteViewController, create a GMSAutocompleteTableDataSource and set it as the UITableView's delegate and data source. For example:
_tableDataSource = [[GMSAutocompleteTableDataSource alloc] init];
_tableDataSource.delegate = self;
tableView.delegate = _tableDataSource;
tableView.dataSource = _tableDataSource;
When the text field text changes, call sourceTextHasChanged on the table data source.
[_tableDataSource sourceTextHasChanged:textField.text];
Finally, have the parent view controller implement the GMSAutocompleteTableDataSourceDelegate protocol
There is some example code in the sample app contained in the GoogleMaps CocoaPod that is close to what you want. Look for SDKDemoAutocompleteWithTextFieldController.m in the downloaded Pods directory.
I used this code to achieve same behaviour you are asking.
-(void)LoadJson_search{
searchArray=[[NSMutableArray alloc]init];
NSLog(#"str......%#",strSearch);
NSString *str1 = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&key=AIzaSyD2NttUhPQ4PKvpju97qpeWj8SYnZtzt0s",strSearch];
NSLog(#"%#",strSearch);
NSURL *url = [NSURL URLWithString:str1];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error=nil;
if(data.length==0)
{
}
else
{
NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"1,,,,%#",jsondic);
[searchArray removeAllObjects];
if([[jsondic objectForKey:#"status"]isEqualToString:#"ZERO_RESULTS"])
{
}
else if([[jsondic objectForKey:#"status"]isEqualToString:#"INVALID_REQUEST"])
{
}
else
{
for(int i=0;i<[jsondic.allKeys count];i++)
{
//['predictions'][0]['description']
NSString *str1=[[[jsondic objectForKey:#"predictions"] objectAtIndex:i] objectForKey:#"description"];
[searchArray addObject:str1];
}
tbl_vw1.hidden=FALSE;
}
if (searchArray.count == 0) {
tbl_vw1.hidden = TRUE;
}
else{
[tbl_vw1 reloadData];
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
if (textField.tag == 3) {
strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([string isEqualToString:#" "]){
}
else{
[self LoadJson_search];
}
}
return YES;
}
And on tableview didSelect method use following
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
strSelectedAddress = [searchArray objectAtIndex:indexPath.row];
[self.eventDict setObject:strSelectedAddress forKey:#"venue"];
//[self geoCodeUsingAddress:str_select_address];
tbl_vw1.hidden=TRUE;
[tbl_vw reloadData];
}
after reloading table, use this in cellForRowAtIndexpath to update selected place name.
cell.txt.text = [self.eventDict objectForKey:#"venue"];
Hope this helps you. :)
This is my answer based on # Nij. This will give complete satisfaction you to ...
#import "ViewController.h"
#import <GooglePlaces/GooglePlaces.h>
#interface ViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *searchArray;
NSString *strSearch;
}
#property (weak, nonatomic) IBOutlet UITextField *searchTextfeild;
#property (weak, nonatomic) IBOutlet UITableView *tbl_vw1;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_searchTextfeild.delegate = self;
_tbl_vw1.delegate = self;
_tbl_vw1.dataSource = self;
_tbl_vw1.hidden = YES;
_searchTextfeild.clearButtonMode = UITextFieldViewModeAlways;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)LoadJson_search{
searchArray=[[NSMutableArray alloc]init];
// NSLog(#"str......%#",strSearch);
// This API key is from https://developers.google.com/maps/web/
NSString *str1 = [NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%#&key=AIzaSyAm7buitimhMgE1dKV2j4_7doULluiiDzU", strSearch];
NSURL *url = [NSURL URLWithString:str1];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error=nil;
if(data.length==0)
{
}
else
{
NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
// NSLog(#"1,,,,%#",jsondic);
[searchArray removeAllObjects];
if([[jsondic objectForKey:#"status"]isEqualToString:#"ZERO_RESULTS"])
{
}
else if([[jsondic objectForKey:#"status"]isEqualToString:#"INVALID_REQUEST"])
{
}
else
{
for(int i=0;i<[jsondic.allKeys count];i++)
{
NSString *str1=[[[jsondic objectForKey:#"predictions"] objectAtIndex:i] objectForKey:#"description"];
[searchArray addObject:str1];
}
_tbl_vw1.hidden = NO;
// NSLog(#"%#", searchArray);
}
if (searchArray.count == 0) {
_tbl_vw1.hidden = YES;
}else{
[_tbl_vw1 reloadData];
}
}
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
if (textField.tag == 3) {
strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string];
if([string isEqualToString:#" "]){
}else{
[self LoadJson_search];
}
}
return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
_tbl_vw1.hidden = YES;
[_tbl_vw1 reloadData];
return YES;
}
//TableView delegates
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return searchArray.count;
}
-(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
UITableViewCell *cell = [_tbl_vw1 dequeueReusableCellWithIdentifier:#"cell"];
if(!cell) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
// NSLog(#"searchArray ==== %#", searchArray);
cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
_searchTextfeild.text = [searchArray objectAtIndex:indexPath.row];
_tbl_vw1.hidden = YES;
[_tbl_vw1 reloadData];
}

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

Indexed Search similar to the Facebook/Google search engine

Indexed search in a UIViewController! At any letters inserted into the textfield research, a method is called that executes a database query to obtain tuples as a function of string.
If I write a letter after letter, the app crashes because the method is called again while it is still running.
Instead, if I write a letter, look forward to the completion of the dispatch queue and write another letter, everything works! But I would like to perform as described in the first case!
Here the code:
- (IBAction)searchUser:(id)sender{
dispatch_async(dispatch_get_main_queue(), ^{
[_arrID removeAllObjects];
[_arrNames removeAllObjects];
[_arrPictures removeAllObjects];
[self.tableView reloadData];
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
CGRect activityFrame = CGRectMake(self.view.center.x, self.view.center.y, 0.0, 0.0);
_activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:activityFrame];
[[self.view superview] addSubview:_activityIndicator];
_activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
_activityIndicator.color = [UIColor whiteColor];
[_activityIndicator startAnimating];
});
//Here I fill the 3 arrays with details obtained from external queries on database
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
[_activityIndicator stopAnimating];
});
});
}
}
Is there a solution to conduct research in a manner similar to the facebook/google search engine? Given that I don't use UISearchDisplayController, but I just use a textfield that calls the method searchUser every [Editing Did Change] and it filled the Tableview with all results! Please help me!
in your .h file declare the array name
#interface newactivecomposeViewController : UIViewController<
UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate>
{
BOOL SelectionAvailable;
}
#property (strong, nonatomic) NSMutableArray *AllDetails,*SuggestionArray;
#property (strong, nonatomic) UITableView *tablevie;
in your .m file
#synthesize SuggestionArray,AllDetails,tablevie;
- (void)viewDidLoad
{
SuggestionArray=[[NSMutableArray alloc]init]; //for using the searching
self.AllDetails=[[NSMutableArray alloc] init]; //store the all name in this array
tablevie=[[UITableView alloc]initWithFrame:CGRectMake(23, 136, 277, 214)]; //tableview created dynamically
tablevie.dataSource=self;
tablevie.delegate=self;
[self.tablevie registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
[self.view addSubview:tablevie];
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
[SuggestionArray removeAllObjects];
for (NSDictionary *tmp in self.AllDetails) {
NSRange substringRange =[[[tmp objectForKey:#"name"] lowercaseString] rangeOfString:[substring lowercaseString]];
if (substringRange.location==0) {
[SuggestionArray addObject:tmp];
}
}
if ([SuggestionArray count]==0) {
tablevie.hidden=YES;
}
else {
tablevie.hidden=NO;
}
[tablevie reloadData];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
for (NSString *tmp in getfrinendname) {
NSLog(#"%#", tmp);
if ([[textField.text lowercaseString] isEqualToString:[tmp lowercaseString]]) {
textField.text=tmp;
SelectionAvailable=YES;
break;
}
else {
SelectionAvailable=NO;
}
}
if (!SelectionAvailable) {
if (textField.text.length==0)
{
textField.text=#"";
}
// else if (textField.text.length >0)
// {
//
// [textField resignFirstResponder];
// [tablevie setHidden:YES];
//
// }
else
{
Alert=[[UIAlertView alloc]initWithTitle:#"User not found!" message:#"Please try again" delegate:Nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[Alert show];
}
}
#pragma tablevie data source
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"the count==%lu",(unsigned long)[SuggestionArray count]);
return [SuggestionArray 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=[[SuggestionArray objectAtIndex:indexPath.row] objectForKey:#"name"]; //load your key or index
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
yourtextfieldname.text=[NSString stringWithFormat:#"%#",[[SuggestionArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}

UISearchBar misses elements in the non-visible part of the tableView

I have a TableView with many rows, most are not visible at the time of loading viewController. The rows of UITableView are extracted from a SQLite database. How can I make do that the SearchBar search between all rows and not just the visible ones?
In header file:
#interface ExhibitorsViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>{
BOOL isSearchOn;
BOOL canSelectRow;
NSMutableArray * listOfExpositors;
NSMutableArray * searchResult;
}
//....
#end
In implementation file
-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
if(isSearchOn){
return [searchResult count];
//In this array there are the elements after use of searchBar
}else{
int number=[self.mutableArray count];
//In this array there are all elements of database, extracts in viewDidLoad()
return number;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] ;
}
if(isSearchOn){
NSString * cellValue = [searchResult objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
//loading data from the database
Database *currow =[self.mutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = currow.name;
[listOfExpositors addObject:cell.textLabel.text];
//here only loads the list of names visible and not the entire table
//How do I put all the elements in this array?
NSLog(#" %#", listOfExpositors);
isSearchOn = NO;
canSelectRow = YES;
}
}
-(void) doneSearching{
isSearchOn = NO;
canSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self.searchBar resignFirstResponder];
[self.tableView reloadData];
}
-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
isSearchOn = YES;
if(self.searchBar.text.length>0){
canSelectRow=YES;
self.tableView.scrollEnabled = YES;
}else{
canSelectRow= NO;
self.tableView.scrollEnabled = NO;
}
}
-(void) searchExpositorsTableView{
[searchResult removeAllObjects];
for (NSString *str in listOfExpositors){
NSRange titleResultsRange = [str rangeOfString:self.searchBar.text options:
NSCaseInsensitiveSearch];;
if (titleResultsRange.length >0) {
[searchResult addObject:str];
}
}
NSLog(#"%#", searchResult);
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if([searchText length]>0){
canSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchExpositorsTableView];
}else{
canSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[self searchExpositorsTableView];
[self.searchBar resignFirstResponder];
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(canSelectRow){
return indexPath;
}else{
return nil;
}
NSLog(#"%d", indexPath.row);
}
It was wrong to use the array created in cellForRowAtIndexPath because it was limited only to the visible elements. I then used the NSMutableArray created in viewDidLoad () that does contain all the elements of the database. I changed the following methods:
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//....
if(isSearchOn){
NSString * cellValue = [searchResult objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
Database *currow =[self.mutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = currow.name;
//Should be removed this array and used to another, self.mutableArray
//[listOfExpositors addObject:cell.textLabel.text];
// NSLog(#" %#", listOfExpositors);
isSearchOn = NO;
canSelectRow = YES;
}
}
Method for research
-(void) searchExpositorsTableView{
[searchResult removeAllObjects];
for (Database *currow in self.mutableArray){
/*In self.mutableArray there are all elements because is created in
viewDidLoad*/
NSLog(#"list of expositors %#", self.mutableArray);
NSRange titleResultsRange = [currow.name rangeOfString:self.searchBar.text options: NSCaseInsensitiveSearch];
if (titleResultsRange.length >0) {
[searchResult addObject:currow.name];
}
}
NSLog(#"%#", searchResult);
}

Resources