Filter NSMutableDictionary data in UITableView - ios

I need to filter data in UITableview by text entered in UISearchbar. I followed this example but there data in NSMutableArray and I can't alter it under my requirements. My data is NSMutableDictionary. I'm stuck on this for long time.
My data:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDictionary *myDict = [NSDictionary dictionaryWithContentsOfFile:path];
sectionKeys = [NSMutableArray new];
sectionsTitle = [NSMutableArray new];
NSArray *tableArray = [myDict objectForKey:#"Black"];
[resultArray addObject:#"Black"];
[resultDic setValue:tableArray forKey:#"Black"];
[sectionsTitle addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Black"]]];
[sectionCord addObject:[NSString stringWithFormat:#"%#", [tableData valueForKey:#"Coordinates"]]];
[sectionKeys addObject:#"Section1"];
self.tableData = resultDic;
self.sectionsTitle = resultArray;
[myTable reloadData];
My table:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionKeys.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionKeys objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int rowCount;
if(self.isFiltered)
rowCount = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
else
rowCount = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
return rowCount;
}
- (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];
if(isFiltered){
NSDictionary *dict = [[filteredTableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
else{
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
return cell;
}
My search:
#pragma mark - SearchBar Delegate -
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text{
if(text.length == 0)
{
isFiltered = FALSE;
NSLog(#"false");
}
else
{
isFiltered = true;
NSLog(#"true");
filteredTableData = [[NSMutableDictionary alloc] init];
for (MyAnnotation* ann in tableData)
{
NSRange nameRange = [ann.title rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [ann.description rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:ann];
//error
}
}
}
[myTable reloadData];
}

First of all, you need to create a state/flag for the controller/data source, in order for it to know weather you are in search/filter mode.
Then, if you are in search mode, point the data source methods to the filteredArray.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
int numberOfSections = 0;
if (_searchMode)
{
numberOfSections = self.filteredDataDict.allKeys.count;
}
else
{
numberOfSections = self.tableData.allKeys.count;
}
return numberOfSections;
}
Hope it's understood.

Related

How to get all the array values when searching particular values in tableview cell using Obejctive C?

I have implemented a TableView with custom cells with two labels to populate city name and city id (I kept the city id label hidden). Here my problem is when I search for the city name I cannot get the city id also, when I search the city name, I want both the values to be filtered.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"citylocation";
searchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (!cell) {
cell= [[searchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier];
}
if(!isFilltered)
{
cell.textLabel.text = [avahotel objectAtIndex:indexPath.row];
cell.city.text = [[createdDate objectAtIndex:indexPath.row]stringValue];
}else
{
cell.textLabel.text = [filteredString objectAtIndex:indexPath.row];
}
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isFilltered)
{
return [filteredString count];
}
return [avahotel count];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if(searchText.length == 0)
{
isFilltered = NO;
}else
{
isFilltered = YES;
filteredString = [[NSMutableArray alloc]init];
for(NSString *str in avahotel)
{
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[filteredString addObject:str];
}
}
}
[_searchtableview reloadData];
}
Use following code in else part for this method. searchBar textDidChange
Updated
isFilltered = YES;
filteredString = [[NSMutableArray alloc]init];
filteredCityId = [[NSMutableArray alloc]init];
for(Int i=0; i<avahotel.count; i++)
{
NSString *str = [avahotel objectAtIndex:i];
NSRange stringRange = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringRange.location != NSNotFound)
{
[filteredString addObject:[avahotel objectAtIndex:i]];
NSString *strId = [NSString stringWithFormat:#"%d",i];
[filteredCityId addObject:strId]
// here your both filter array declare.filteredcityId and filteredString
}
}

UISegmentedControl in iOS

I am using UISegmentedControl and using UITableView but my query is segment button 1 click and display data for yes and 2 button click and display data from no and adding A to Z section UITableView first button click properly data display and properly tableview section atoz display but 2 button click and app crash `
 #import "ZnameViewController.h"
#import "ZpaleoViewController.h"
#import "SWRevealViewController.h"
#interface ZnameViewController ()
#end
#implementation ZnameViewController
#synthesize strname1,sagmentController,objtbl,name;
- (void)viewDidLoad {
[super viewDidLoad];
SWRevealViewController *revealViewController = self.revealViewController;
if ( revealViewController )
{
[self.slide setTarget: self.revealViewController];
[self.slide setAction: #selector( revealToggle: )];
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
}
appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
databse = [FMDatabase databaseWithPath:appdelegate.appDBPath];
[arrCatname removeAllObjects];
[arrPaleo removeAllObjects];
arrCatname = [[NSMutableArray alloc]init];
arrPaleo = [[NSMutableArray alloc]init];
arrStatus = [[NSMutableArray alloc]init];
arrCat2 = [[NSMutableArray alloc]init];
arrSta2 = [[NSMutableArray alloc]init];
[self segmentSwitch:self];
// Do any additional setup after loading the view.
}
- (IBAction)segmentSwitch:(id)sender {
[databse open];
NSString *selectQuery = [NSString stringWithFormat:#"select * from Food ORDER BY name ASC"];
NSLog(#"%#",selectQuery);
FMResultSet *resultQuary = [databse executeQuery:selectQuery];
while ([resultQuary next]) {
// NSString *z_paleo = [resultQuary stringForColumn:#"status"];
z_paleo = [NSString stringWithFormat:#"%d",[resultQuary intForColumn:#"status"]];
if ([z_paleo isEqualToString:#"1"]) {
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrPaleo addObject:#""];
}
else{
[arrPaleo addObject:z_name];
}
[arrSta2 addObject:z_paleo];
}
else{
if(z_name == nil || [z_name isKindOfClass:[NSNull null]])
{
[arrCatname addObject:#""];
}
else
{
[arrCatname addObject:z_name];
}
[arrCat2 addObject:z_paleo];
}
}
[databse close];
if(sagmentController.selectedSegmentIndex == 0)
{
if ([z_paleo isEqualToString:#"1"]) {
[self getName:arrPaleo];
objtbl.hidden = NO;
}
}
else if (sagmentController.selectedSegmentIndex == 1)
{
if ([z_paleo isEqualToString:#"0"]) {
[self getName:arrCatname];
objtbl.hidden = NO;
}
}
[objtbl reloadData];
}
-(void)getName:(NSMutableArray *)arr
{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < arr.count; i++)
{
NSString *string = [arr objectAtIndex:i];
dict = [[NSMutableDictionary alloc] init];
[dict setObject:string forKey:#"Name"];
[dict setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict];
}
[temp addObject:temp2];
sorted = [[NSArray alloc] initWithArray:temp];
}
-(void)getname2:(NSMutableArray *)array{
NSMutableArray *temp = [[NSMutableArray alloc] init];
NSMutableArray *temp2 = [[NSMutableArray alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *string = [array objectAtIndex:i];
dict1 = [[NSMutableDictionary alloc] init];
[dict1 setObject:string forKey:#"Name"];
[dict1 setObject:[NSNumber numberWithInt:i] forKey:#"ID"];
NSString *firstString = [string substringToIndex:1];
if([temp2 containsObject:firstString] == NO || temp2.count == 0)
{
if(temp2.count != 0)
{
[temp addObject:temp2];
temp2 = [[NSMutableArray alloc] init];
}
[temp2 addObject:firstString];
}
[temp2 addObject:dict1];
}
[temp addObject:temp2];
sorted1 = [[NSArray alloc] initWithArray:temp];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
int i = 0;
for(NSArray *array in sorted)
{
NSString *string = [array objectAtIndex:0];
if([string compare:title] == NSOrderedSame)
break;
i++;
}
return i;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (sagmentController.selectedSegmentIndex == 0) {
return [sorted count];
}else {
return [sorted count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSArray *array = [sorted objectAtIndex:section];
return [array objectAtIndex:0];
//return [foodIndexTitles objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
NSMutableArray *titleArray = [NSMutableArray array];
[titleArray addObject:#"A"];
[titleArray addObject:#"B"];
[titleArray addObject:#"C"];
[titleArray addObject:#"D"];
[titleArray addObject:#"E"];
[titleArray addObject:#"F"];
[titleArray addObject:#"G"];
[titleArray addObject:#"H"];
[titleArray addObject:#"I"];
[titleArray addObject:#"J"];
[titleArray addObject:#"K"];
[titleArray addObject:#"L"];
[titleArray addObject:#"M"];
[titleArray addObject:#"N"];
[titleArray addObject:#"O"];
[titleArray addObject:#"P"];
[titleArray addObject:#"Q"];
[titleArray addObject:#"R"];
[titleArray addObject:#"S"];
[titleArray addObject:#"T"];
[titleArray addObject:#"U"];
[titleArray addObject:#"V"];
[titleArray addObject:#"W"];
[titleArray addObject:#"X"];
[titleArray addObject:#"Y"];
[titleArray addObject:#"Z"];
return titleArray;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if (sagmentController.selectedSegmentIndex == 1) {
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}else{
NSArray *array = [sorted objectAtIndex:section];
return (array.count - 1);
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellIdentifire = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifire];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifire];
}
if (sagmentController.selectedSegmentIndex == 0) {
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"Yes_check.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
}
else
{
NSArray *array = [sorted objectAtIndex:indexPath.section];
dict = [array objectAtIndex:indexPath.row + 1];
cell.textLabel.text = [dict objectForKey:#"Name"];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"No.png"]];
[cell.accessoryView setFrame:CGRectMake(0, 0, 15, 15)];
return cell;
}
return cell;
}

IndexPath.row changes when using search issue?

I am trying to successfully implement a UISearchcontroller into my UITableview however I have the following issues, I pass data using the indexPath.row method to the next view controller and the indexPath.row changes when I search, secondly I am using multiple arrays for my data in my tableview, and so what i've done is created another array that holds all of the other arrays content in one and searches through that, and it all works perfectly except when I want to pass my data because the indexPath.row changes instead of staying with the cell (which is what i need to happen). Please could you check out my code and see if you can help?
#import "AbsViewController.h"
#interface AbsViewController ()
#end
#implementation AbsViewController {
//these are all my arrays
//The arrays that carry for no equipment.
NSArray *tableData;
NSArray *thumbnails;
NSArray *sets;
NSArray *reps;
NSArray *instructions;
NSArray *materials;
NSArray *status;
NSArray *tips;
NSArray *difficulty;
NSArray *target;
//The arrays that carry for equipment.
NSArray *tableData1;
NSArray *thumbnails1;
NSArray *sets1;
NSArray *reps1;
NSArray *instructions1;
NSArray *materials1;
NSArray *status1;
NSArray *tips1;
NSArray *difficulty1;
NSArray *target1;
//The arrays that carry for bosu ball.
NSArray *tableData2;
NSArray *thumbnails2;
NSArray *sets2;
NSArray *reps2;
NSArray *instructions2;
NSArray *materials2;
NSArray *status2;
NSArray *tips2;
NSArray *difficulty2;
NSArray *target2;
//The arrays that carry for physio ball.
NSArray *tableData3;
NSArray *thumbnails3;
NSArray *sets3;
NSArray *reps3;
NSArray *instructions3;
NSArray *materials3;
NSArray *status3;
NSArray *tips3;
NSArray *difficulty3;
NSArray *target3;
//The arrays that carry for weighted.
NSArray *tableData4;
NSArray *thumbnails4;
NSArray *sets4;
NSArray *reps4;
NSArray *instructions4;
NSArray *materials4;
NSArray *status4;
NSArray *tips4;
NSArray *difficulty4;
NSArray *target4;
//Search array
NSArray *tableData5;
NSArray *status5;
NSArray *thumbnails5;
//The array for the search results.
NSArray *searchResults;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Abdominal";
//Here im initializing my arrays.
// Find out the path of my array.
NSString *path = [[NSBundle mainBundle] pathForResource:#"Abs" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
tableData = [dict objectForKey:#"name"];
thumbnails = [dict objectForKey:#"imageFile"];
status = [dict objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path1 = [[NSBundle mainBundle] pathForResource:#"Abs1" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict1 = [[NSDictionary alloc] initWithContentsOfFile:path1];
tableData1 = [dict1 objectForKey:#"name"];
thumbnails1 = [dict1 objectForKey:#"imageFile"];
status1 = [dict1 objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path2 = [[NSBundle mainBundle] pathForResource:#"Abs2" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict2 = [[NSDictionary alloc] initWithContentsOfFile:path2];
tableData2 = [dict2 objectForKey:#"name"];
thumbnails2 = [dict2 objectForKey:#"imageFile"];
status2 = [dict2 objectForKey:#"status"];
// Find out the path of recipes.plist
NSString *path3 = [[NSBundle mainBundle] pathForResource:#"Abs3" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict3 = [[NSDictionary alloc] initWithContentsOfFile:path3];
tableData3 = [dict3 objectForKey:#"name"];
thumbnails3 = [dict3 objectForKey:#"imageFile"];
status3 = [dict3 objectForKey:#"status"];
NSString *path4 = [[NSBundle mainBundle] pathForResource:#"Abs4" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict4 = [[NSDictionary alloc] initWithContentsOfFile:path4];
tableData4 = [dict4 objectForKey:#"name"];
thumbnails4 = [dict4 objectForKey:#"imageFile"];
status4 = [dict4 objectForKey:#"status"];
//this is the array that carries all the content.
NSString *path5 = [[NSBundle mainBundle] pathForResource:#"AbsTotal" ofType:#"plist"];
// Load the file content and read the data into arrays
NSDictionary *dict5 = [[NSDictionary alloc] initWithContentsOfFile:path5];
tableData5 = [dict5 objectForKey:#"name"];
status5 = [dict5 objectForKey:#"status"];
thumbnails5 = [dict5 objectForKey:#"thumbnails"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if (self.searchDisplayController.isActive) {
return 1;
}
return 5 ;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
}
else if (section == 0) {
return [tableData count];
}
else if (section == 1) {
return [tableData1 count];
}
else if (section == 2) {
return [tableData2 count];
}
else if (section == 3) {
return [tableData3 count];
}
else if (section == 4) {
return [tableData4 count];
}
else {
return [tableData5 count];
}
}
//this is my cellForRowAtIndexPath method.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"ExerciseCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
}
else if (indexPath.section == 0) {
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 1) {
cell.textLabel.text = [tableData1 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status1 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails1 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 2) {
cell.textLabel.text = [tableData2 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status2 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails2 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 3) {
cell.textLabel.text = [tableData3 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status3 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails3 objectAtIndex:indexPath.row]];
}
else if (indexPath.section == 4) {
cell.textLabel.text = [tableData4 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status4 objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails4 objectAtIndex:indexPath.row]];
}
else {
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Type: %#", [status objectAtIndex:indexPath.row]];
cell.imageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
}
return cell;
}
//this is where i've attempted to fix the issue but didn't work.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSInteger rowNumber = 0;
for (NSInteger i = 0; i < indexPath.section; i++) {
rowNumber += [self tableView:tableView numberOfRowsInSection:i];
}
rowNumber += indexPath.row;
NSLog(#"%ld",(long)rowNumber);
}
//this is where i filter my tableview
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", searchText];
searchResults = [tableData5 filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
//Here i create my view for my header/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// create the parent view that will hold header Label
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,25)];
customView.backgroundColor = [UIColor belizeHoleColor];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor belizeHoleColor];
headerLabel.font = [UIFont fontWithName:#"Avenir-Black" size:14];
headerLabel.frame = CGRectMake(6,0,320,25);
if (section == 1) {
headerLabel.text = #"";
}
if (section == 2) {
headerLabel.text = #"";
}
if (section == 3) {
headerLabel.text = #"";
}
if (section == 4) {
headerLabel.text = #"";
}
if (section == 0) {
headerLabel.text = #"";
}
headerLabel.textColor = [UIColor cloudsColor];
[customView addSubview:headerLabel];
return customView;
}
please if someone could help that would sooooooo appreciated.
thanks in advance.
//u can do this on - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath method first get
if (tableView == self.searchDisplayController.searchResultsTableView)
{
NSString *PassData = [tableData5 objectAtIndex:indexPath.row];
// NSString *passData = nil; //COMMENT THIS LINE SINCE IT CONTAINS SELECTED VALUE FROM SEARCH DISPLAY TABLEVIEW NO NEED TO BE ST NULL AGAIN "COMMENT THIS LINE AND TRY"
NSString *selectedStatus = nil;
UIImage *selectedThumbImage = nil;
//assuming ur array's contains equal number of objects
if([tableData containsObject:passData]) //if the search results contains an object in this array
{
//by using passData from search results tableview's tapped row u cn get all the below grouped tableview data now do for other array's
int index = [tableData indexOfObject:passData]; //get the index of selected array
selectedStatus = [status objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails objectAtIndex:index];//get thumbnil image from index
}
else if ([tableData1 containsObject:passData])
{
int index = [tableData1 indexOfObject:passData]; //get the index of selected array
selectedStatus = [status1 objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails1 objectAtIndex:index];//get thumbnil image from index
}
else if ([tableData2 containsObject:passData])
{
int index = [tableData2 indexOfObject:passData]; //get the index of selected array
selectedStatus = [status2 objectAtIndex:index]; //from that index get the status data
selectedThumbImage = [thumbnails2 objectAtIndex:index];//get thumbnil image from index
}
else if (//check for otehr remaining array)
{
//grab all details
}
//at the end your passData contains title , selectedStatus contains status , and selectedThumbImage contains thumb image use it to pass
}//end if (tableView == self.searchDisplayController.searchResultsTableView)

Can't implement search filter to my table data using NSPredicate

Now my search work by sectionsTitle, if I write "Category1" or "Category2" it find section Category1, or Category2, but I need to search by NAMES in all this sections, from here:
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
[NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
What I need to change in my code for search by Names? Now I'm confused with all that NSArray's, NSMutableArray's and NSDictionary :(
I load my data like this:
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
sectionKeys = [NSMutableArray new];
sectionsTitle = [NSMutableArray new];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"blueKey"])
{
ann = [dict objectForKey:#"Category1"];
[resultArray addObject:#"Category1"];
[resultDic setValue:ann forKey:#"Category1"];
[sectionKeys addObject:#"Section 1"];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"yellowKey"])
{
ann = [dict objectForKey:#"Category2"];
[resultArray addObject:#"Category2"];
[resultDic setValue:ann forKey:#"Category2"];
[sectionKeys addObject:#"Section 2"];
}
self.tableData = resultDic;
self.sectionsTitle = resultArray;
[myTable reloadData];
This is how I filter data:
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"SELF contains[cd] %#",
searchText];
searchResults = [sectionsTitle filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
This is how my table look like:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return 1;
}else{
return sectionKeys.count;
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return #"Search";
}else{
return [sectionKeys objectAtIndex:section];
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
int num = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
return num;
}
}
- (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];
if (tableView == self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
} else {
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Avenir" size: 16.0];
cell.detailTextLabel.font = [UIFont fontWithName:#"Avenir" size: 12.0];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Name"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [dict objectForKey:#"Address"]];
}
return cell;
}
My data structure:
With a simplified data set (only the Name entry included in the dictionaries), this should reproduce your setup:
NSArray *categories = #[
#[#{#"Name":#"Joe"}, #{#"Name":#"Jane"}],
#[#{#"Name":#"Anne"}, #{#"Name":#"Bob"}]
];
Then the ANY operator of NSPredicate will find the array you are after:
NSString *nameToSearch = #"Bob";
NSPredicate *catPred = [NSPredicate predicateWithFormat:#"ANY Name = %#", nameToSearch];
To see how this predicate can filter your category array:
NSArray *filteredCats = [categories filteredArrayUsingPredicate:catPred];
BTW, you might get less confused if you build some custom objects to hold your data instead of relying only on arrays and dictionaries.

How to set titleForHeaderInSection manually

I load data from plist to uitableview like this:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSMutableDictionary *resultDic = [[NSMutableDictionary alloc] init];
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
NSDictionary *myDict = [NSDictionary dictionaryWithContentsOfFile:path];
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"purpleKey"])
{
NSArray *purple = [myDict objectForKey:#"Purple"];
[resultArray addObject:#"Purple"];
[resultDic setValue:purple forKey:#"Purple"];
}
if ([[NSUserDefaults standardUserDefaults] boolForKey:#"orangeKey"])
{
NSArray *orange = [myDict objectForKey:#"Orange"];
[resultArray addObject:#"Orange"];
[resultDic setValue:orange forKey:#"Orange"];
}
self.tableData = resultDic;
self.sectionsTitle = resultArray;
}
titleForHeaderInSection
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionsTitle objectAtIndex:section];
}
my plist structure
My question is:
How can I manually set title for Purple header and Orange header without to changing names in plist file?
like this: Purple = Category 1, Orange = Category 2
EDIT
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return sectionsTitle.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionsTitle objectAtIndex:section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int num = [[tableData objectForKey:[sectionsTitle objectAtIndex:section]] count];
if (num > 3) {
num = 3;
}
return num;
}
// 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *dict = [[tableData objectForKey:[sectionsTitle objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.numberOfLines = 1;
cell.textLabel.font = [UIFont systemFontOfSize:11];
cell.textLabel.text = [NSString stringWithFormat:#"%# - %#", [dict objectForKey:#"Name"], [dict objectForKey:#"Address"]];
if ([dict objectForKey:#"Address"] == (NULL)) {
//do nothing
}
return cell;
}
From the look of your code, the section headers are coming from resultsArray, which you are populating with the constant strings Orange and Purple.
You can just put different constant strings into that array, unless I'm missing something.
So, instead of
[resultArray addObject:#"Orange"];
Use
[resultArray addObject:#"Category 1"];

Resources