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)
Related
When my user searches for something inside a tableview, when no results are returned, my app shows the standard "No Results" placeholder inside the tableview. That said, when no results exist, I want to return one populated cell (cell populated with default data). How can I accomplish this? I tried the below, but I still get 'No Results' returned?
ViewController.m
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
if ([searchResults count] == 0) {
return 1;
} else {
return [searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *NetworkTableIdentifier = #"sidebarCell";
self.sidetableView.separatorStyle = UITableViewCellSeparatorStyleNone;
sidebarCell *cell = (sidebarCell *)[tableView dequeueReusableCellWithIdentifier:NetworkTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"sidebarCell" owner:self options:nil];
cell = nib[0];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSDictionary *userName = searchResults[indexPath.row];
NSString *first = userName[#"first name"];
NSString *last = userName[#"last name"];
[[cell username] setText:[NSString stringWithFormat:#"%# %#", first, last]];
NSDictionary *userlast = searchResults[indexPath.row];
[[cell lastName] setText:userlast[#"last name"]];
NSDictionary *userBio = searchResults[indexPath.row];
[[cell userDescription] setText:userBio[#"userbio"]];
NSString *area = userName[#"neighbourhood"];
NSString *city = userName[#"city"];
[[cell areaLabel] setText:[NSString stringWithFormat:#"%#, %#", area, city]];
NSString *profilePath = searchResults[indexPath.row][#"photo_path"];
[cell.usermini sd_setImageWithURL:[NSURL URLWithString:profilePath]];
if ([searchResults count] == 0) {
NSLog(#"SEARCH RESULTS ARE %#", searchResults);
[[cell username] setText:[NSString stringWithFormat:#"%#", self.searchBar.text]];
[[cell lastName] setText:userlast[#""]];
[[cell userDescription] setText:#"This friend is not on the app (yet!) Tap to invite them."];
[[cell areaLabel] setText:[NSString stringWithFormat:#""]];
NSString *profileDefault = #"http://url.com/user.png";
[cell.usermini sd_setImageWithURL:[NSURL URLWithString:profileDefault]];
return cell;
}
return cell;
}
I don't really recommend doing this, as you should return an empty list, if there are no search results. That is consistent with User Interface Guidelines. But, if you insist, you could create a default object and initialize your searchResults array with that object and return 1 from the numberOfRows method. Something like this:
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
if ([searchResults count] == 0) {
NSDictionary *dict = [NSDictionary dictionaryWithObjects:#[#“Enter First Name”, #“Enter Last Name”, #“Enter User Bio”, #“Enter Neighborhood”, #“Enter City”, #“Enter Photo Path”]
forKeys: #[#“first_name”, #“last_name, #“userbio”, #“neighbourhood”, #“city”, #“photo_path”];
searchResults = [NSArray arrayWithObjects: dict, nil];
return 1;
}
else {
return [searchResults count];
}
}
And, you can greatly simplify your cellForRowAtIndexPath code as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *NetworkTableIdentifier = #"sidebarCell";
self.sidetableView.separatorStyle = UITableViewCellSeparatorStyleNone;
sidebarCell *cell = (sidebarCell *)[tableView dequeueReusableCellWithIdentifier:NetworkTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"sidebarCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
//Note, I like to name my local variables the same as the dictionary keys just to eliminate any confusion
NSDictionary *userObject = [searchResults objectAtIndex:indexPath.row];
NSString *first_name = [userObject objectForKey:#"first name"];
NSString *last_name = [userObject objectForKey:#"last name"];
NSString *userbio = [userObject objectForKey:#“userbio”];
NSString *neighbourhood = [userObject objectForKey:#“neighbourhood”];
NSString *city = [userObject objectForKey:#“city”];
NSString *photo_path = [userObject objectForKey:#“photo_path”];
[[cell username] setText:[NSString stringWithFormat:#"%# %#", first_name, last_name]];
[[cell lastName] setText:last_name];
[[cell userDescription] setText:userbio];
[[cell areaLabel] setText:[NSString stringWithFormat:#"%#, %#", neighbourhood, city]];
[[cell usermini] sd_setImageWithURL:[NSURL URLWithString:photo_path]];
}
return cell;
}
I did something like this in my app. It's ugly and I'm not recommending you following this way. I did it only because I was kind of lazy about layouts and placing the placeholder in the correct place in the view hierarchy and handle all those hide/show situations. My view controller has a very complex hierarchy of views and the table view was one that has already had all I needed (resize automatically when the status or toolbar is showing).
What I suggest you is to hide the table view when there is an empty search result and substitute it with your placeholder.
Try this it's working:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if (arrData.count>0)
{
self.TblView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
self.TblView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.TblView.bounds.size.width, self.TblView.bounds.size.height)];
noDataLabel.text = #"No Results";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
self.TblView.backgroundView = noDataLabel;
self.TblView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
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.
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.
I would like to make a selection like this
How can I change my
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
delegate method to work in accordance with my requirement.
Why so complicated? Just deselect all cells of the same section before the user selects a new one.
First allow multiple selection for your UITableView. Then implement this delegate method:
Swift 3 version:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
for vcip in tableView.indexPathsForSelectedRows ?? [] {
if vcip.section == indexPath.section && vcip.item != indexPath.item {
tableView.deselectRow(at: vcip, animated: false)
}
}
return indexPath
}
Keep a property in your view controller called selectedRow, which represents the indexPath of tableview that represents the checked item in a table section.
In your view controller's -tableView:cellForRowAtIndexPath: delegate method, set the accessoryType of the cell to UITableViewCellAccessoryCheckmark if the cell's indexPath equals the selectedRow indexpath value. Otherwise, set it to UITableViewCellAccessoryNone.
In your view controller's -tableView:didSelectRowAtIndexPath: delegate method, set the selectedRow value to the indexPath.row that is selected, e.g.: self.selectedRow = indexPath.row
This won't be a good solution.
Use a NSMutableArray for storing the selected sections.
NSMutableArray *selectedSections; //instance variable
selectedSections= [[NSMutableArray alloc] init]; //in viewDidLoad
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSNumber *section = [NSNumber numberWithInt:indexPath.section];
if([selectedSections containsObject:section]
return nil;
else
{
[selectedSections addObject:section];
return indexPath;
}
}
When you deselect a row write the below code there:
[selectedSections removeObject:[NSNumber numberWithInt:indexPath.section]];
LimeRed has a great answer elsewhere in this thread, but it is not complete. The key issue is that the OP needs to have the accessory checkmark removed. Simply calling deselectRow will not remove the checkmark. Per the documentation, deselectRow does not call the delegate method tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) where the removal of the checkmark code might be located. Therefore you need handle this removal as part of the code that LimeRed wrote.
Here is a more complete implementation that removes the accessory checkmark again based on LimeRed's solution:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?
{
for path in tableView.indexPathsForSelectedRows ?? []
{
if path.section == indexPath.section && path.item != indexPath.item
{
let cell = tableView.cellForRow(at: path)
cell?.accessoryType = UITableViewCellAccessoryType.none
tableView.deselectRow(at: path, animated: false)
}
}
return indexPath
}
try like this,
In .h
#property (nonatomic, retain) NSIndexPath *checkedIndexPath;
In .m
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.section==0)
{
// to check and Uncheck the row
if(self.checkedIndexPath)
{
UITableViewCell* uncheckCell = [tableView1
cellForRowAtIndexPath:self.checkedIndexPath];
uncheckCell.accessoryType = UITableViewCellAccessoryNone;
}
if([self.checkedIndexPath isEqual:indexPath])
{
self.checkedIndexPath = nil;
}
else
{
UITableViewCell* cell = [tableView1 cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
self.checkedIndexPath = indexPath;
}
}
}
This one's gonna be ViewController.h
#interface ViewController : UITableViewController
{
NSMutableArray *list;
NSMutableArray *sectionList;
NSIndexPath *oldIndexPath0;
int row0;
NSIndexPath *oldIndexPath1;
int row1;
NSIndexPath *oldIndexPath2;
int row2;
NSIndexPath *oldIndexPath3;
int row3;
NSString *othersString;
NSString *timeString;
NSString *pRoomString;
NSString *parkingString;
NSString *smokingString;
NSString *select0;
NSString *select1;
NSString *select2;
NSString *select3;
}
#end
This one's ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewWillAppear:(BOOL)animated
{
// initial row by 100;
row0 = 100;
row1 = 100;
row2 = 100;
row3 = 100;
// initial strings by #”"
othersString = [NSString stringWithFormat:#""];
timeString = [NSString stringWithFormat:#""];
pRoomString = [NSString stringWithFormat:#""];
parkingString = [NSString stringWithFormat:#""];
smokingString = [NSString stringWithFormat:#""];
select0 = #"";
select1 = #"";
select2 = #"";
select3 = #"";
// Get row index
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/rowString.txt"];
NSData *rowData = [fileManager contentsAtPath:fileName];
// From NSData to NSString
NSString *rowString = [[NSString alloc] initWithData:rowData encoding:NSUTF8StringEncoding];
if (rowString) {
// spit row string
NSArray *rowArray = [rowString componentsSeparatedByString:#":"];
for (int i=0; i<[rowArray count]; i++) {
NSString *indexVal = [rowArray objectAtIndex:i];
if ([indexVal length] != 0) {
// set row value
if (i == 0) {
NSString *row0Str = [rowArray objectAtIndex:0];
row0 = [row0Str intValue];
}
if (i == 1) {
NSString *row1Str = [rowArray objectAtIndex:1];
row1 = [row1Str intValue];
}
if (i == 2) {
NSString *row2Str = [rowArray objectAtIndex:2];
row2 = [row2Str intValue];
}
if (i == 3) {
NSString *row3Str = [rowArray objectAtIndex:3];
row3 = [row3Str intValue];
}
}
}
}
// Update the view with current data before it is displayed.
[super viewWillAppear:animated];
//Initialize the array.
list = [[NSMutableArray alloc] initWithCapacity:0];
sectionList = [[NSMutableArray alloc] initWithCapacity:0];
// section header
NSArray *sectionHeaderArray = [NSArray arrayWithObjects:#"01",#"02",#"03",#"04", nil];
NSDictionary *sectionHeaderDic = [NSDictionary dictionaryWithObject:sectionHeaderArray forKey:#"section"];
[sectionList addObject:sectionHeaderDic];
// time list
NSArray *timeArray = [NSArray arrayWithObjects:#"time 01",#"time 01",#"time 01", nil];
NSDictionary *timeDic = [NSDictionary dictionaryWithObject:timeArray forKey:#"time"];
// private room
NSArray *pRoomArray = [NSArray arrayWithObjects:#"room 01",#"room 02", nil];
NSDictionary *pRoomDic = [NSDictionary dictionaryWithObject:pRoomArray forKey:#"pRoom"];
// parking
NSArray *parkingArray = [NSArray arrayWithObjects:#"park 01",#"park 02",#"park 03", nil];
NSDictionary *parkingDic = [NSDictionary dictionaryWithObject:parkingArray forKey:#"parking"];
// smoking
NSArray *smokingArray = [NSArray arrayWithObjects:#"smoke 01",#"smoke 02",#"smoke 03", nil];
NSDictionary *smokingDic = [NSDictionary dictionaryWithObject:smokingArray forKey:#"smoking"];
// add all dictionary to list
[list addObject:timeDic];
[list addObject:pRoomDic];
[list addObject:parkingDic];
[list addObject:smokingDic];
// Scroll the table view to the top before it appears
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//Number of section
return [list count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:section];
NSArray *array;
switch (section) {
case 0:
// time array
array = [dictionary objectForKey:#"time"];
break;
case 1:
// pRoom array
array = [dictionary objectForKey:#"pRoom"];
break;
case 2:
// parking array
array = [dictionary objectForKey:#"parking"];
break;
case 3:
// smoking array
array = [dictionary objectForKey:#"smoking"];
break;
default:
break;
}
//Number of rows
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Budget";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
UITableViewCellStyleSubtitle;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array;
switch (indexPath.section) {
case 0:
// time array
array = [dictionary objectForKey:#"time"];
if (indexPath.row == row0 ) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 1:
// pRoom array
array = [dictionary objectForKey:#"pRoom"];
if (indexPath.row == row1) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 2:
// parking array
array = [dictionary objectForKey:#"parking"];
if (indexPath.row == row2) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
case 3:
// smoking array
array = [dictionary objectForKey:#"smoking"];
if (indexPath.row == row3) {
cell.accessoryType=UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
break;
default:
break;
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
NSLog(#"index cell");
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *title = nil;
//Get the dictionary object
NSDictionary *dictionary = [sectionList objectAtIndex:0];
NSArray *array = [dictionary objectForKey:#"section"];
title = [array objectAtIndex:section];
return title;
}
#pragma mark -
#pragma mark Table view selection
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
switch(indexPath.section)
{
case 0:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row0 = 100;
timeString = #"";
}else {
NSIndexPath *SIndexPath0 = [NSIndexPath indexPathForRow:row0 inSection:0];
if ([[tableView cellForRowAtIndexPath:SIndexPath0 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath0] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath0 == nil) {
oldIndexPath0 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath0 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath0];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"time"];
timeString = [array objectAtIndex:indexPath.row];
row0 = indexPath.row;
oldIndexPath0 = nil;
}
select0 = #"marked";
break;
}
case 1:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row1 = 100;
pRoomString = #"";
}else {
NSIndexPath *SIndexPath1 = [NSIndexPath indexPathForRow:row1 inSection:1];
if ([[tableView cellForRowAtIndexPath:SIndexPath1 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath1] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath1 == nil) {
oldIndexPath1 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath1 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath1];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"pRoom"];
pRoomString = [array objectAtIndex:indexPath.row];
row1 = indexPath.row;
oldIndexPath1 = nil;
}
select1 = #"marked";
break;
}
case 2:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row2 = 100;
parkingString = #"";
}else {
NSIndexPath *SIndexPath2 = [NSIndexPath indexPathForRow:row2 inSection:2];
if ([[tableView cellForRowAtIndexPath:SIndexPath2 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath2] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath2 == nil) {
oldIndexPath2 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath2 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath2];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"parking"];
parkingString = [array objectAtIndex:indexPath.row];
row2 = indexPath.row;
oldIndexPath2 = nil;
}
select2 = #"marked";
break;
}
case 3:
{
UITableViewCell *cell1 = [tableView cellForRowAtIndexPath:indexPath];
if ([[tableView cellForRowAtIndexPath:indexPath ] accessoryType] == UITableViewCellAccessoryCheckmark) {
cell1.accessoryType = UITableViewCellAccessoryNone;
row3 = 100;
smokingString = #"";
}else {
NSIndexPath *SIndexPath3 = [NSIndexPath indexPathForRow:row3 inSection:3];
if ([[tableView cellForRowAtIndexPath:SIndexPath3 ] accessoryType] == UITableViewCellAccessoryCheckmark) {
[[tableView cellForRowAtIndexPath:SIndexPath3] setAccessoryType:UITableViewCellAccessoryNone];
}
if (oldIndexPath3 == nil) {
oldIndexPath3 = indexPath;
}
UITableViewCell *cell2 = nil;
if (oldIndexPath3 != indexPath) {
cell2 = [tableView cellForRowAtIndexPath:oldIndexPath3];
}
cell1.accessoryType = UITableViewCellAccessoryCheckmark;
if (cell2) {
cell2.accessoryType = UITableViewCellAccessoryNone;
}
//Get the dictionary object
NSDictionary *dictionary = [list objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"smoking"];
smokingString = [array objectAtIndex:indexPath.row];
row3 = indexPath.row;
oldIndexPath3 = nil;
}
select3 = #"marked";
break;
}
default:
break;
}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
// Cancle button and add an event handler
self.navigationItem.leftBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Cancle"
style:UIBarButtonSystemItemCancel
target:self
action:#selector(handleCancle:)];
// Cancle button and add an event handler
self.navigationItem.rightBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Use"
style:UIBarButtonItemStyleBordered
target:self
action:#selector(handleUse:)];
}
- (void) handleCancle:(id)sender
{
// pop the controller
[self.navigationController popViewControllerAnimated:YES];
}
- (void) handleUse:(id)sender{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *fileName;
// Get row index value
fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/othersString.txt"];
NSData *rowValData = [fileManager contentsAtPath:fileName];
// From NSData to NSString
NSString *rowValString = [[NSString alloc] initWithData:rowValData encoding:NSUTF8StringEncoding];
NSString *oldTimeString = #"";
NSString *oldpRoomString = #"";
NSString *oldParkingString = #"";
NSString *oldSmokingString = #"";
if (rowValString) {
// spit row string
NSArray *rowValArray = [rowValString componentsSeparatedByString:#":"];
for (int i=0; i<[rowValArray count]; i++) {
if ([rowValArray objectAtIndex:i] != #"") {
// set row value
if (i == 0 ) {
oldTimeString = [rowValArray objectAtIndex:0];
}
if (i == 1 ) {
oldpRoomString = [rowValArray objectAtIndex:1];
}
if (i == 2 ) {
oldParkingString = [rowValArray objectAtIndex:2];
}
if (i == 3) {
oldSmokingString = [rowValArray objectAtIndex:3];
}
}
}
}
if (select0 == #"") {
timeString = oldTimeString;
}
if (select1 == #"") {
pRoomString = oldpRoomString;
}
if (select2 == #"") {
parkingString = oldParkingString;
}
if (select3 == #"") {
smokingString = oldSmokingString;
}
// make othersString string
othersString = [NSString stringWithFormat:#"%#:%#:%#:%#", timeString, pRoomString, parkingString, smokingString];
// write othersString to othersString.txt file
fileName= [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/othersString.txt"];
NSData *othersData = [othersString dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:fileName contents:othersData attributes:nil];
// make row data in string
NSString *rowString = [NSString stringWithFormat:#"%i:%i:%i:%i", row0,row1,row2,row3];
// write othersString to othersString.txt file
fileName = [NSHomeDirectory() stringByAppendingPathComponent:#"tmp/rowString.txt"];
NSData *rowData = [rowString dataUsingEncoding:NSUTF8StringEncoding];
[fileManager createFileAtPath:fileName contents:rowData attributes:nil];
// pop the controller
[self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
[list release];
}
#end
Got this stuff from this post, as this was in Japanese I changed it. Thanks to the author.
After a lot of modifications I have arrived with this
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [aTableView cellForRowAtIndexPath:indexPath];
if(indexPath.section == 0)
{
if([section1Rows count] == 0)
{
[section1Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section1Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section1Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section1Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
if(indexPath.section == 1)
{
if([section2Rows count] == 0)
{
[section2Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section2Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section2Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section2Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
if(indexPath.section == 2)
{
if([section3Rows count] == 0)
{
[section3Rows addObject:[NSNumber numberWithInt:indexPath.row]];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
[section3Rows removeObjectAtIndex:0];
for (UITableViewCell *cell in [tabview visibleCells]) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
[section3Rows addObject:[NSNumber numberWithInt:indexPath.row]];
NSLog(#"%#",section3Rows);
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
}
I'll explain the problem in steps,
I have selected a row in 3 sections, If I select a row again in any of the sections... then everything goes haywire. How can I deselect the previously selected row and highlight the then selected row?
Thanks.
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"];