UISearchDisplayController / UISearchResultsTableView Adding in Extra Line with Each Search ? iOS7 - ios

I have a UISearchDisplayController which is behaving strangely under iOS7. The first time I do a search, everything is ok and the UISearchResultsTableView displays the results correctly.
The problem is that the second time I do a search (after dismissing the table), a blank line (looks like a cell) is added to the top of the search results table :
Each subsequent search then adds in another blank line to the top of the table, and so on and so on.
Here is the code :
//Setup the search bar.
searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 360.0f, 44.0f)];
UIBarButtonItem * searchBarButton = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
searchBar.delegate = self;
controller = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
controller.searchResultsDataSource = self;
controller.searchResultsDelegate = self;
self.tabBarController.navigationItem.rightBarButtonItems = #[searchBarButton];
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if (isLoading) {
return;
}
[self filter : searchText];
[controller.searchResultsTableView reloadData];
}
- (void)filter : (NSString *)text {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(name CONTAINS[cd] %# OR number CONTAINS[cd] %#)", text, text];
searchResults = [standArray filteredArrayUsingPredicate:predicate];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [searchResults count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if ([searchResults count] ==0) {
cell.textLabel.text = #"";
}
else {
NSString * name = [[searchResults objectAtIndex:indexPath.row] name];
NSString * number = [[searchResults objectAtIndex:indexPath.row] number];
NSString * resultsString = [NSString stringWithFormat:#"%# %#", name, number];
cell.textLabel.text = resultsString;
}
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSString * name = [[searchResults objectAtIndex:indexPath.row] name];
Object * exhibitor = [self getExhibitorForStandName:standName];
if ([exhibitor.companyName isEqualToString:standName]) {
NSString * status = [[self getExhibitorForStandName:standName] status];
cell.backgroundColor = [standColourMapping objectForKey:status];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.searchDisplayController setActive:NO animated:YES];
...
}
}

Ok for future travellers, this looks like a weird bug whereby the height of the UISearchBar is added to the top of the searchResultsTable each subsequent time it appears.
The solution is the following :
controller.searchResultsTableView.contentInset = UIEdgeInsetsMake(0.0f, 0.f, 0.f, 0.f); //Fix for weird weird iOS7 bug where each subsequent
//search adds the height of the searchBar to the top of the searchResultsTableView.

Related

UISearchController touches in safe area when press inside the search bar in Objective-C

I have one tableview and I created one UISearchController programmatically and added to tableview.
Initially it looks good but when I press on inside the search bar it looks below.
I don't want to keep my searchbar in navigation bar. And I can not use UITableViewController.
Find the code below which I implemented.
My .h file
#property (strong, nonatomic) UISearchController *searchController;
NSMutableArray *tableData;
NSArray *filteredContentList;
My .m file
// New SearchController.
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.delegate = self;
self.searchController.searchBar.searchBarStyle = UISearchBarStyleProminent;
[self.searchController.searchBar sizeToFit];
self.tblUserList.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
#pragma mark - UISearchDisplayDelegate
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = searchController.searchBar.text;
NSPredicate *resultPredicate;
//resultPredicate = [NSPredicate predicateWithFormat:#"displayname contains[c] %#",searchString];
resultPredicate = [NSPredicate predicateWithFormat:#"value contains[c] %#", searchString];
filteredContentList = [tableData filteredArrayUsingPredicate:resultPredicate];
//filteredContentList = [[tableData valueForKey:#"data"] filteredArrayUsingPredicate:resultPredicate];
[self.tblUserList reloadData];
}
- (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope {
[self updateSearchResultsForSearchController:self.searchController];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
CGRect searchBarFrame = self.searchController.searchBar.frame;
[self.tblUserList scrollRectToVisible:searchBarFrame animated:NO];
return NSNotFound;
}
I want to show my searchbar above the tableview not in naviationbar.
Thanks in advance.
Late answer by myself.
I use UITextFiled instead of UISearchBar. Below is my code implementation.
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
And my textFieldDidChange method
-(void)textFieldDidChange:(UITextField *)textField
{
searchTextString=textField.text;
[self updateSearchArray:searchTextString];
}
-(void)updateSearchArray:(NSString *)searchText {
if(searchText.length==0) {
isFilter=NO;
} else {
isFilter=YES;
filteredContentList = [[NSMutableArray alloc]init];
NSPredicate *resultPredicate;
resultPredicate = [NSPredicate predicateWithFormat:#"value contains[c] %#", searchText];
filteredContentList = [tableData filteredArrayUsingPredicate:resultPredicate];
[self.tblUserList reloadData];
}
}
And my TableView methods:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSInteger numOfSections = 0;
if ([filteredContentList count] || [tableData count]) {
_tblUserList.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
_tblUserList.backgroundView = nil;
} else {
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _tblUserList.bounds.size.width, _tblUserList.bounds.size.height)];
noDataLabel.text = NSLocalizedString(#"No Users found", #"Message");
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
_tblUserList.backgroundView = noDataLabel;
_tblUserList.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
/*if (isSearching) {
return [filteredContentList count];
}
else {
return [tableData count];
}*/
if (isFilter) {
return [filteredContentList count];
} else {
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] valueForKeyPath:#"data.displayname"];
// Configure the cell...
if (isFilter) {
//cell.textLabel.text = [filteredContentList objectAtIndex:indexPath.row];
cell.textLabel.text = [[filteredContentList objectAtIndex:indexPath.row] valueForKeyPath:#"data.displayname"];
}
else {
cell.textLabel.text = [[tableData objectAtIndex:indexPath.row] valueForKeyPath:#"data.displayname"];
}
return cell;
}

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 add a search bar and search display to an rss feed in UItableview

I created an RSS reader that parses from a .xml file. I am trying to create a search bar and search display controller, but am not sure how to search the objectForKey "title" or objectForKey "summary" within the UITableView.
Any help would be greatly appreciated.
The numberOfRowsInSection and cellForRowAtIndexPath looked like this:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return self.parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
I recently tried to follow this sample project - https://github.com/deepthit/TableViewSearch.git - based on a suggestion.
My code then looked like this:
#interface QldRecentJudgmentsViewController () {
__strong NSArray *mFilteredArray_;
__strong UISearchBar *mSearchBar_;
__strong UISearchDisplayController *mSearchDisplayController_;
}
#end
#implementation ViewController
#synthesize parseResults = _parseResults, HUD;
- (void)viewDidLoad {
[super viewDidLoad];
mSearchBar_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0,
0,
self.view.bounds.size.width,
44)];
mSearchBar_.delegate = self;
mSearchBar_.placeholder = #"search";
self.tableView.tableHeaderView = mSearchBar_;
mSearchDisplayController_ = [[UISearchDisplayController alloc] initWithSearchBar:mSearchBar_
contentsController:self];
mSearchDisplayController_.searchResultsDelegate = self;
mSearchDisplayController_.searchResultsDataSource = self;
mSearchDisplayController_.delegate = self;
}
#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.
//return self.parseResults.count;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
return [mFilteredArray_ count];
}
return parseResults.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id result;
if (tableView == self.searchDisplayController.searchResultsTableView ||
[mFilteredArray_ count] > 0)
{
result = [mFilteredArray_ objectAtIndex:indexPath.row];
}
else
{
result = [parseResults objectAtIndex:indexPath.row];
}
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//Check if cell is nil. If it is create a new instance of it
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure titleLabel
cell.textLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
cell.textLabel.numberOfLines = 2;
//Configure detailTitleLabel
cell.detailTextLabel.text = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"summary"];
cell.detailTextLabel.numberOfLines = 2;
//Set accessoryType
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Set font and style
cell.selectionStyle = UITableViewCellSelectionStyleGray;
cell.textLabel.font = [UIFont boldSystemFontOfSize:14];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *url = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"link"];
NSString *title = [[self.parseResults objectAtIndex:indexPath.row] objectForKey:#"title"];
WebViewController *viewController = [[WebViewController alloc] initWithURL:url title:title];
[self.navigationController pushViewController:viewController animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#pragma mark - UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText {
if ([searchText length] == 0)
{
[self.tableView reloadData];
return;
}
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.title contains[cd] %# OR SELF.summary contains[cd] %#", searchText, searchText];
mFilteredArray_ = [self.parseResults filteredArrayUsingPredicate:predicate];
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
mFilteredArray_ = nil;
[self.tableView reloadData];
}
However, when I follow this the RSS feed does not load anymore in the tableview, so there are no results. Nevertheless when I try to search it does not correctly search the "title" or "summary" and the search results do not appear correctly -the cells are not neatly aligned after searching for something and getting results. Also, the only way to see RSS in the tableview is to search for any generic string, but once you press cancel in the search bar the RSS feed disappears and shows an empty tableview.
Thanks for any help in advance.

Selecting Cell in Table IOS

I am trying to create a method that changes the string object "tableColorName" to the cell selected. The tableData NSArray consists of object: "red","blue","green". I want to save the string "tableColorName" to redColor if red is selected, blueColor if blue, greenColor if green. After the cell is selected I want the viewController to go back to the root. I appreciate your help in advance:
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int theRow = indexPath.row;
NSString *tableColorName;
tableColorName = [[NSString alloc] initWithString:([_tableData [theRow] stringValue],#"Color")];
[self.navigationController popToRootViewControllerAnimated:YES];
}
//first of all take one NSArray and
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.colorNames = [[NSArray alloc] initWithObjects:#"Red", #"Green",
#"Blue", #"Indigo", #"Violet", nil];
}
// Implement Table method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
// Customize the appearance of table view cells.
- (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] autorelease];
}
// Configure the cell.
self.navigationItem.title=#"Colors";
UIImage *cellImage = [UIImage imageNamed:#"a.png"];
cell.imageView.image = cellImage;
NSString *colorString = [self.colorNames objectAtIndex: [indexPath row]];
cell.textLabel.text = colorString;
NSString *subtitle = [NSString stringWithString: #"All about the color "];
subtitle = [subtitle stringByAppendingFormat:colorString];
cell.detailTextLabel.text = subtitle;
return cell;
}
- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
{
int idx = indexPath.row;
obj.lbl.text=[#"You select "stringByAppendingString:[colorNames objectAtIndex:idx]];
[self popToViewController animated:YES];
}
Try this ::
NSArray *arr;
NSString *tableColorName; // Use in AppDelegate
- (void)viewDidLoad
{
arr = [[NSArray alloc] initWithObjects:#"Red", #"Green", #"Blue", nil];
}
Table View Methods ::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.title.text = [NSString stringWithFormat:#"%#", [arr objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
app.tableColorName = [NSString StringWithFormat:#"%# Color", [arr objectAtIndex:indexPath.row]];
[self.navigationController popToRootViewControllerAnimated:YES];
}
Then, access by app.tableColorName whenever you want to display.
Thanks.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//do whatever with the selected cell.
//go back to the root
}

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