Unable to keep Table row is selected - ios

In my app, I used a splitView. There are 3 different tables.
When I select any row from 1st Table, the display in the detail view & row remains selected in Left side menu. However, when I select any row from 2nd or 3rd Table, the row is just highlighted with blue color & quickly disappear the Selected blue (i.e. it does not remain Highlighted).
Help me solve this problem.
My code as follow:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if(tableView == tbl_class)
{
btnEdit1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btnEdit1 setFrame:CGRectMake(220, 15, 20, 20)];
[btnEdit1 addTarget:self action:#selector(btnEditPressed:) forControlEvents:UIControlEventTouchUpInside];
[btnEdit1 setImage:[UIImage imageNamed:#"edit-3-black.png"] forState:UIControlStateNormal];
UIButton *btnDelete = [UIButton buttonWithType:UIButtonTypeCustom];
[btnDelete setFrame:CGRectMake(260, 15, 20, 20)];
[btnDelete addTarget:self action:#selector(btnDelete:) forControlEvents:UIControlEventTouchUpInside];
[btnDelete setImage:[UIImage imageNamed:#"recycle-bin2.png"] forState:UIControlStateNormal];
[btnEdit1 setTag:indexPath.row];
[btnDelete setTag:indexPath.row];
cell.textLabel.text=[NSString stringWithFormat:#"%#",[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_name"]];
if(! isEditing)
{
[cell.contentView addSubview:btnEdit1];
[cell.contentView addSubview:btnDelete];
}
}
if(tableView==tbl_assessment)
{
if (classNames.count > 0)
{
[btnAddAssesst setHidden:NO];
}
else
{
[btnAddAssesst setHidden:YES];
}
cell.textLabel.text=[NSString stringWithFormat:#"%#",[[assessment_list objectAtIndex:indexPath.row]valueForKey:#"assessment_name"]];
}
if (tableView==tbl3)
{
cell.textLabel.text=[arr_result objectAtIndex:indexPath.row];
}
cell.textLabel.font=[UIFont fontWithName:#"Trebuchet MS" size:17.0f];
cell.textLabel.textColor=[UIColor grayColor];
return cell;
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
/*
When a row is selected, set the detail view controller's detail item to the item associated with the selected row.
*/
//NSUInteger row = indexPath.row;
if (aTableView==tbl_class)
{
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
self.secondDetailViewController=[[[Class_Vice_ViewController alloc]init]autorelease];
[viewControllerArray addObject:self.secondDetailViewController];
self.appDelegate.splitViewController.delegate = self.secondDetailViewController;
[[NSUserDefaults standardUserDefaults]setInteger:[[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_id"]intValue] forKey:#"psel_class"];
[self databaseOpen];
assessment_list=[[NSMutableArray alloc]init];
NSString *qq=[NSString stringWithFormat:#"select * from Assessment where class_id=%d",[[[classNames objectAtIndex:indexPath.row]valueForKey:#"class_id"]intValue]];
assessment_list=[[database executeQuery:qq]mutableCopy];
[database close];
if (classNames.count > 0)
{
[btnAddAssesst setHidden:NO];
}
else
{
[btnAddAssesst setHidden:YES];
}
if (!assessment_list.count==0) {
[tbl_assessment setHidden:NO];
[btnDelete setHidden:NO];
[tbl_assessment reloadData];
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
[tbl_assessment reloadData];
}
else if (aTableView==tbl_assessment)
{
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
self.thirdDetailViewController=[[[GameAssessment alloc]init]autorelease];
[viewControllerArray addObject:self.thirdDetailViewController];
self.appDelegate.splitViewController.delegate = self.thirdDetailViewController;
[[NSUserDefaults standardUserDefaults]setInteger:[[[assessment_list objectAtIndex:indexPath.row]valueForKey:#"assessment_id"]intValue] forKey:#"ASSESSMENT_ID"];
[self databaseOpen];
assessment_list=[[NSMutableArray alloc]init];
NSString *qq=[NSString stringWithFormat:#"select * from Assessment where class_id=%d",[[NSUserDefaults standardUserDefaults]integerForKey:#"psel_class"]];
assessment_list=[[database executeQuery:qq]mutableCopy];
[database close];
if (!assessment_list.count==0) {
[tbl_assessment setHidden:NO];
[tbl_assessment reloadData];
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
}
else {
[self.appDelegate.splitViewController viewWillDisappear:YES];
NSMutableArray *viewControllerArray=[[NSMutableArray alloc] initWithArray:[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] viewControllers]];
[viewControllerArray removeLastObject];
if (indexPath.row==0) {
self.fifthViewController=[[[ResultStudent_vice alloc]init]autorelease];
[viewControllerArray addObject:self.fifthViewController];
self.appDelegate.splitViewController.delegate = self.fifthViewController;
}
if (indexPath.row==1) {
self.fourthDetailViewController=[[[ResultClass_vice alloc]init]autorelease];
[viewControllerArray addObject:self.fourthDetailViewController];
self.appDelegate.splitViewController.delegate = self.fourthDetailViewController;
}
[[self.appDelegate.splitViewController.viewControllers objectAtIndex:1] setViewControllers:viewControllerArray animated:NO];
[self.appDelegate.splitViewController viewWillAppear:YES];
}
}

Two things to do to keep the row as selected
-deselectRowAtIndexpath should not be there in didselectRowAtIndexpath
Keep an NSMutableArray of NSIndexpath for storing the selected value .When a row is selected add it to array and in the -cellForRowAtIndexpath method check the indexpath is there in cell and if it is there make [tablecell setSelected:YES]; otherwise NO

Related

Why Image is getting swap after delete from array in Objective c

I am new in iOS and I am facing problem regarding to delete image
For delete I am using code like this
In DidFinishLoading
imageArray =[[NSMutableArray alloc]init];
for (int i=0; i<idarray.count; i++) {
[imageArray addObject:[UIImage new]];
}
In CellForrowAtIndexPath
cell.btnRemove.tag=indexPath.row;
[cell.btnRemove addTarget:self action:#selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
Button Click
-(void)btnRemoveClick:(UIButton *)sender
{
UIAlertView *Alertview =[[UIAlertView alloc] initWithTitle:#"Warning!" message:#"Are You Sure you want to delete Image" delegate:self cancelButtonTitle:#"NO" otherButtonTitles:#"YES", nil];
[Alertview show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
[imageArray removeObjectAtIndex:CurrentIndexPath];
[imageArray addObject:[UIImage new]];
[Audittable reloadData];
}
But When I delete image image get swap as in the image
enter image description here
enter image description here
CellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
AuditNextTableViewCell *cell = (AuditNextTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AuditNextTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
cell.audittitlelbl.text=[NSString stringWithFormat:#"%#",[idarray objectAtIndex:indexPath.row]];
cell.nameidlbl.text=[NSString stringWithFormat:#"%#",[CheckpointNameIDArray objectAtIndex:indexPath.row]];
cell.passlbl.text=[NSString stringWithFormat:#"%#",[Passarray objectAtIndex:indexPath.row]];
cell.faillbl.text=[NSString stringWithFormat:#"%#",[Failarray objectAtIndex:indexPath.row]];
cell.warninglbl.text=[NSString stringWithFormat:#"%#",[Warningarray objectAtIndex:indexPath.row]];
cell.nalbl.text=[NSString stringWithFormat:#"%#",[NAarray objectAtIndex:indexPath.row]];
cell.popuplbl.text=[NSString stringWithFormat:#"%#",[Popuparray objectAtIndex:indexPath.row ]];
// cell.remarklbl.text=[NSString stringWithFormat:#"%#",[PFWNAArray objectAtIndex:indexPath.row]];
DataModel *model2 = [AuditTextBoxarray objectAtIndex:indexPath.row];
cell.lblAuditTextBox.text=model2.AuditTextBoxString;
//cell.lblAuditTextBox.text=[NSString stringWithFormat:#"%#",[AuditTextBoxarray objectAtIndex:indexPath.row]];
cell.AuditCountlbl.text=[NSString stringWithFormat:#"%ld)", (long)indexPath.row +1];
cell.CaptureImage.image = [imageArray objectAtIndex:indexPath.row];
// tag add on buttons
cell.passbtn.tag = indexPath.row;
cell.failbtn.tag = indexPath.row;
cell.wipbtn.tag = indexPath.row;
cell.nabtn.tag = indexPath.row;
cell.Photobtn.tag=indexPath.row;
cell.btnRemove.tag=indexPath.row;
//method add on buttons
[cell.passbtn addTarget:self action:#selector(btnP:) forControlEvents:UIControlEventTouchUpInside];
[cell.failbtn addTarget:self action:#selector(btnF:) forControlEvents:UIControlEventTouchUpInside];
[cell.wipbtn addTarget:self action:#selector(btnW:) forControlEvents:UIControlEventTouchUpInside];
[cell.nabtn addTarget:self action:#selector(btnNA:) forControlEvents:UIControlEventTouchUpInside];
[cell.Photobtn addTarget:self action:#selector(btnphotoClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.btnRemove addTarget:self action:#selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"AuditPost"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
ComplareArray=[devices valueForKey:#"checkpointid"];
countcellbtn.text=[NSString stringWithFormat:#"%lu",(unsigned long)ComplareArray.count];
if (![arrIndexPaths containsObject:indexPath])
{
[arrIndexPaths addObject:indexPath];
}
if (![PassarrIndexPaths containsObject:indexPath])
{
[PassarrIndexPaths addObject:indexPath];
}
//background color change on button
DataModel *model = [arrData objectAtIndex:indexPath.row];
if([model.strSelected isEqualToString:#"P"])
{
cell.passbtn.backgroundColor = [UIColor redColor];
}
else if([model.strSelected isEqualToString:#"F"])
{
cell.failbtn.backgroundColor = [UIColor yellowColor];
}
else if([model.strSelected isEqualToString:#"W"])
{
cell.wipbtn.backgroundColor = [UIColor orangeColor];
}
else if([model.strSelected isEqualToString:#"NA"])
{
cell.nabtn.backgroundColor = [UIColor blueColor];
}
else if ([model.strSelected isEqualToString:#"PA"])
{
cell.passbtn.backgroundColor=[UIColor greenColor];
}
else if ([model.strSelected isEqualToString:#"NAA"])
{
cell.nabtn.backgroundColor=[UIColor blueColor];
}
else
{
cell.passbtn.backgroundColor = [UIColor lightGrayColor];
cell.failbtn.backgroundColor = [UIColor lightGrayColor];
cell.wipbtn.backgroundColor = [UIColor lightGrayColor];
cell.nabtn.backgroundColor = [UIColor lightGrayColor];
}
[cell.contentView.layer setBorderColor:[UIColor blackColor].CGColor];
[cell.contentView.layer setBorderWidth:0.5f];
return cell;
}

Objective-C: Change UIImageView in Custom Cell change different cell images

I am using a custom cell on UITableView with multi Section and i’m added a UITapGestureRecognizer to a UIImageView for change it when the image is selected but When I select the image other's images in different cell are selected as well.
This is the code for the TableView datasource method cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"FilterCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
UILabel *text = (UILabel *)[cell viewWithTag:ROW_TITLE];
UIImageView *image = (UIImageView *)[cell viewWithTag:ROW_IMAGE];
NSDictionary *item = [results objectAtIndex:indexPath.section];
NSString *string = [item objectForKey:JSONResp_common_name];
[text setText:((string != [NSNull null])? string : #"")];
if ([[item objectForKey:JSONResp_common_status] isEqualToNumber:[NSNumber numberWithBool:YES]])
[image setImage:[UIImage imageNamed:#"checked"]];
else
[image setImage:[UIImage imageNamed:#"unchecked"]];
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
[image setTag:indexPath.row];
[image setUserInteractionEnabled:YES]; action:#selector(handleTapFrom:)];
if([self tableView:tableView
canCollapseSection:indexPath.section]){ // EXPANDABLE ROW
if(!indexPath.row){// HEADER
// SET ACCESORIES
if([expandedSections containsIndex:indexPath.section])
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"menos"]]];
else
[cell setAccessoryView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mas"]]];
[image setUserInteractionEnabled:NO];
//Remove checked option from a cell
for(UITapGestureRecognizer *tapGesture in cell.gestureRecognizers)
[cell removeGestureRecognizer:tapGesture];
}else{// SUB ROWS
NSArray *subValues = [item objectForKey:PARAM_STRUCT_SUBELEMENTS];
NSDictionary *detail = [subValues objectAtIndex:indexPath.row -1];
//REASING VALUES TO SUB VALUES
if(detail && [detail isKindOfClass:[City class]]){
City *currentCity = (City *)detail;
[text setText:[currentCity name]];
}
[cell setAccessoryView:nil];
[tapGestureRecognizer setDelegate:self];
[cell addGestureRecognizer:tapGestureRecognizer];
}
}else{//ROWS CHECKED OPTION
[cell setAccessoryView:nil];
[tapGestureRecognizer setDelegate:self];
[cell addGestureRecognizer:tapGestureRecognizer];
}
return cell;
}
</code>
</pre>
This is the code for the TableView datasource method didSelectRowAtIndexPath:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *data = [self.results objectAtIndex:indexPath.section];
if([self tableView:tableView
canCollapseSection:indexPath.section]){
if(!indexPath.row){// EXPANDABLE
// only first row toggles expandaed/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if(currentlyExpanded){
rows = [self tableView:tableView
numberOfRowsInSection:section];
[expandedSections removeIndex:section];
}else{
[expandedSections addIndex:section];
rows = [self tableView:tableView
numberOfRowsInSection:section];
}
for(int i = 1; i < rows; i++){
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(currentlyExpanded){
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"mas"]];
}else{
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"menos"]];
}
}else{// Detail
}
}else{ // Normal Row
//[]
}}
This is the code for the TableView datasource method fro the UITapGestureRecognizer
- (void)handleTapFrom:(UITapGestureRecognizer *)recognizer {
UITableViewCell *cellView = (UITableViewCell *)[recognizer view];
UIImageView *switchImageView = nil;
for (UIView *item in [[[cellView subviews] firstObject] subviews]) {
if ([item isKindOfClass:[UIImageView class]] && ((UIImageView *)item).image != nil) {
switchImageView = (UIImageView *)item;
break;
}
}
if (switchImageView == nil) {
for (UIView *item in [[[[[cellView subviews] firstObject] subviews] objectAtIndex:1] subviews]) {
if ([item isKindOfClass:[UIImageView class]] && ((UIImageView *)item).image != nil) {
switchImageView = (UIImageView *)item;
break;
}
}
}
NSDictionary *item = [results objectAtIndex:switchImageView.tag];
if ([Utility image:switchImageView.image
isEqualTo:[UIImage imageNamed:IMAGE_UNCHECKED]]) {
if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_sortings]) {
[delegate didCheckFilter:item
withStatus:YES];
} else if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_filters]) {
[switchImageView setImage:[UIImage imageNamed:IMAGE_CHECKED]]; //change to a selected image
[delegate didCheckFilter:[item objectForKey:JSONResp_common_type]
withStatus:YES];
}
} else {
if ([[item objectForKey:JSONResp_common_action] isEqualToString:JSONResp_filters]) {
[switchImageView setImage:[UIImage imageNamed:IMAGE_UNCHECKED]];
[delegate didCheckFilter:[item objectForKey:JSONResp_common_type]
withStatus:NO];
}
}}
While declaring the UITapGestureRecognizer on particular cell assign the tag as
cell.tag = indexPath.row;
[cell addGestureRecognizer:tapGestureRecognizer];
and in your handler do like this
- (void)handleTapFrom:(UITapGestureRecognizer *)recognizer {
UITableViewCell *cellView = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:recognizer.tag inSection:0]];
// your stuff
}
Hope this Helps!

When I run app that time I will expand all cell in tableview

I am new in iOS developer. When I run the the app than time iI
but I will get this type of output.
Here is my code
- (void) iterateItems:(NSArray*) array
{
level++;
for (int i = 0; i < [array count]; i++)
{
commentInfo = [array objectAtIndex:i];
//NSLog(#"data=%#",commentInfo);
Item *item = [[Item alloc] init];
item.Id = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
item.parentId = [[[commentInfo objectForKey:#"sub_items"]objectAtIndex:0]objectForKey:#"name"];
if (item.level == 0)
{
item.title =[commentInfo objectForKey:#"dates"];
item.title1 =[commentInfo objectForKey:#"id"];
}
else
{
item.title=#"abc";
}
//NSLog(#"title is=%#",[commentInfo objectForKey:#"status"]);
item.level = level;
item.visibility = #"normal";
item.childVisibility = #"normal";
[items addObject:item];
[self iterateItems:[commentInfo objectForKey:#"sub_items"]];
}
level--;
}
- (float) cellHeightForRow:(int) row
{
Item *item = [items objectAtIndex:row];
if ([item.visibility isEqualToString:#"hidden"])
{
return 0.0f;
}
else
{
return 50.0f;
}
}
- (void) hideCompleteNode:(UISwipeGestureRecognizer*) gestureRecognizer
{
UITableViewCell *cell = (UITableViewCell*) [[gestureRecognizer view] superview];
NSIndexPath *indexPath = [self.tblView indexPathForCell:cell];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
if ([item.childVisibility isEqualToString:#"normal"])
{
[self hideChilds:indexPath];
}
}
else
{
int prevIndex = indexPath.row-1;
if (prevIndex >= 0)
{
Item *parentItem = [items objectAtIndex:prevIndex];
while (parentItem.level != 0)
{
prevIndex--;
if (prevIndex >= 0)
parentItem = [items objectAtIndex:prevIndex];
else
break;
}
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:prevIndex inSection:0];
[self hideChilds:indexPath];
}
}
- (void) hideChilds:(NSIndexPath*) indexPath
{
NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithObjects:indexPath, nil];
Item *item = [items objectAtIndex:indexPath.row];
BOOL shouldHide = [item.childVisibility isEqualToString:#"hidden"]?NO:YES;
item.childVisibility = shouldHide?#"hidden":#"normal";
int nextIndex = indexPath.row+1;
if (nextIndex < [items count])
{
Item *childItem = [items objectAtIndex:nextIndex];
while (childItem.level > item.level)
{
childItem.visibility = shouldHide?#"hidden":#"normal";
childItem.childVisibility = shouldHide?#"hidden":#"normal";
[indexPaths addObject:[NSIndexPath indexPathForRow:nextIndex inSection:0]];
nextIndex++;
if (nextIndex < [items count])
childItem = [items objectAtIndex:nextIndex];
else
break;
}
}
[self.tblView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark -
#pragma mark - UITableView Datasource and Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellHeightForRow:indexPath.row];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"itemCell";
UITableViewCell *cell = [self.tblView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
UIImageView *arrowImgView = [[UIImageView alloc] init];
[arrowImgView setBackgroundColor:[UIColor clearColor]];
[arrowImgView setTag:1];
[cell.contentView addSubview:arrowImgView];
UILabel *titleLbl = [[UILabel alloc] init];
[titleLbl setFont:[UIFont fontWithName:#"HelveticaNeue" size:13.0f]];
[titleLbl setTextColor:[UIColor blackColor]];
titleLbl.textAlignment = NSTextAlignmentCenter;
[titleLbl setTag:2];
[titleLbl setBackgroundColor:[UIColor clearColor]];
[cell.contentView addSubview:titleLbl];
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:#selector(hideCompleteNode:)];
[swipeGesture setDirection:UISwipeGestureRecognizerDirectionLeft];
[cell.contentView addGestureRecognizer:swipeGesture];
}
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
[cell.contentView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"cell_background.png"]]];
}
else
{
[cell.contentView setBackgroundColor:[UIColor clearColor]];
}
UIImageView *arrowImgView = (UIImageView*) [cell viewWithTag:1];
UILabel *titleLbl = (UILabel*) [cell viewWithTag:2];
if ([item.visibility isEqualToString:#"hidden"])
{
[titleLbl setFrame:CGRectZero];
[arrowImgView setFrame:CGRectZero];
}
else
{
[arrowImgView setFrame:CGRectMake(5.0f+(20.0f*item.level), 20.0f, 10.0f, 10.0f)];
if ([item.childVisibility isEqualToString:#"hidden"])
{
[arrowImgView setImage:[UIImage imageNamed:#"closeArrow"]];
}
else
{
[arrowImgView setImage:[UIImage imageNamed:#"openArrow"]];
}
[titleLbl setFrame:CGRectMake(20.0f+(20.0f*item.level), 10.0f, 320.0f - (20.0f+(20.0f*item.level)), 30.0f)];
[titleLbl setText:item.title];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.layer.shadowOpacity = 0.3;
cell.layer.shadowColor = [UIColor blueColor].CGColor;
cell.layer.shadowOffset = CGSizeMake(0.0, 4);
[tblView setSeparatorColor:[UIColor redColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
[tblView setSeparatorColor:[UIColor blackColor]];
tblView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
// [self hideChilds:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = (UITableViewCell *)[self.tblView cellForRowAtIndexPath:indexPath];
cell.contentView.backgroundColor = [UIColor colorWithRed:0.004 green:0.482 blue:0.776 alpha:1];
[self hideChilds:indexPath];
Item *item = [items objectAtIndex:indexPath.row];
if (item.level == 0)
{
}
else
{
Item *item = [items objectAtIndex:indexPath.row];
NSLog(#"value=%#",[NSString stringWithFormat:#"%#",item.title1]);
approveleaseoffer *secondViewController =
[self.storyboard instantiateViewControllerWithIdentifier:#"approveleaseofferpage"];
secondViewController.offer_number=[NSString stringWithFormat:#"%#",item.title1];
[self.navigationController pushViewController:secondViewController animated:YES];
}
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([cell respondsToSelector:#selector(setSeparatorInset:)]) {
[cell setSeparatorInset:UIEdgeInsetsZero];
}
if ([cell respondsToSelector:#selector(setLayoutMargins:)]) {
[cell setLayoutMargins:UIEdgeInsetsZero];
}
}
-(void)viewDidLayoutSubviews
{
if ([tblView respondsToSelector:#selector(setSeparatorInset:)]) {
[tblView setSeparatorInset:UIEdgeInsetsZero];
}
if ([tblView respondsToSelector:#selector(setLayoutMargins:)]) {
[tblView setLayoutMargins:UIEdgeInsetsZero];
}
}
Try changing the line item.childVisibility = #"normal"; to item.childVisibility = #"hidden";
in iterateItems method.

How to save multiple items when user selects from a uitableview to nsuserdefaults?

I am trying to save any of the items as user selects from a uitableview to nsuserdefaults. At that moment only the most recent selection is saved. I would like to have the user to be able to select any of the rows they want and then saved to nsuserdefaults and then use that info anywhere in the app.
thanks for any help
here's my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// categories array
listOfCategories = [[NSMutableArray alloc] init];
[listOfCategories addObject:#"Food & Drinks"];
[listOfCategories addObject:#"Beauty & Wellness"];
[listOfCategories addObject:#"Sports & Fun Activities"];
[listOfCategories addObject:#"Labor & Services"];
[listOfCategories addObject:#"Clothes & Accessories"];
[listOfCategories addObject:#"Education & Training"];
[listOfCategories addObject:#"Products"];
// add label
UIView *viewForHeader = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
UILabel *categoryLabel = [[UILabel alloc] initWithFrame:CGRectMake(10,0,80,30)];
categoryLabel.text = #"Select all:";
[categoryLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
categoryLabel.textColor = [UIColor lightGrayColor];
// add switch
onoff = [[UISwitch alloc] initWithFrame: CGRectMake(100.0f, 0.0f, 100.0f, 0.0f)];
[onoff addTarget: self action: #selector(flipSwitch:) forControlEvents:UIControlEventValueChanged];
[viewForHeader addSubview:onoff];
[viewForHeader addSubview:categoryLabel];
self.tableView.tableHeaderView = viewForHeader;
}
// uiswitch button
- (IBAction) flipSwitch: (id) sender {
onoff = (UISwitch *) sender;
NSLog(#"%#", onoff.on ? #"On" : #"Off");
if (onoff.on) {
for (NSInteger s = 0; s < self.tableView.numberOfSections; s++) {
for (NSInteger r = 0; r < [self.tableView numberOfRowsInSection:s]; r++) {
[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:r inSection:s]
animated:NO
scrollPosition:UITableViewScrollPositionNone];
}
}
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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 [listOfCategories count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
} // Configure the cell...
NSString *cellValue = [listOfCategories objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int index = indexPath.row; id obj = [listOfCategories objectAtIndex:index];
//This toggles the checkmark
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
UIImage *image = [UIImage imageNamed:#"icon-tick.png"];
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downloadButton setImage:image forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 19, 19)];
[downloadButton setBackgroundColor:[UIColor clearColor]];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//This sets the array
} else
{
cell.accessoryType = UITableViewCellAccessoryNone;
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[downloadButton setTitle:#"" forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 0, 0)];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;
}
// Save text of the selected cell:
UITableViewCell *cellSelected = [tableView cellForRowAtIndexPath:indexPath];
if ([cellSelected.textLabel.text isEqualToString:#"Food & Drinks"]) {
NSString *valueToSave = cellSelected.textLabel.text;
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
}
NSString *valueToSave = cellSelected.textLabel.text;
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"preferenceName"];
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"preferenceName"];
NSLog(#"savedValue %#", savedValue);
NSMutableData *data = [NSMutableData data];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// Customize archiver here
[archiver encodeObject:obj forKey:#"keyForYourArrayOfNSIndexPathObjects"];
[archiver finishEncoding];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"keyForYourArrayOfNSIndexPathObjects"];
NSKeyedUnarchiver *unarchiver;
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
[[NSUserDefaults standardUserDefaults] objectForKey:#"keyForYourArrayOfNSIndexPathObjects"]];
// Customize unarchiver here
categoryItemSelected = [unarchiver decodeObjectForKey:#"keyForYourArrayOfNSIndexPathObjects"];
[unarchiver finishDecoding];
NSLog(#"list of categories selected %#", categoryItemSelected);
}
#end
The issue is because you overridden the previously saved data.
So first of all you need to load saved data:
NSKeyedUnarchiver *unarchiver;
unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:
[[NSUserDefaults standardUserDefaults] objectForKey:#"keyForYourArrayOfNSIndexPathObjects"]];
// Customize unarchiver here
categoryItemSelected = [unarchiver decodeObjectForKey:#"keyForYourArrayOfNSIndexPathObjects"];
[unarchiver finishDecoding];
if (categoryItemSelected == nil) {
//If it isn't been created - then create new array
}
Then add new object:
[categoryItemSelected addObject: obj];
And then save it back to UserDefautls

Trouble with Cells in UITableView

I'm writing a simple checklist app. I have two UIViewControllers. The first displays the checklist in a UITableView. I'm using a UIBarButtonItem to push a second view onto the stack to add new tasks. All of the tasks are saved in an array.
Everything works great save for one thing.
If I enter edit mode and delete an item from the table view, the item is removed from the table view and the array--this part seems to be working fine. However, after deleting an item, if I tap the bar button item to add a new task, I run into a problem.
My NSLogs tell me that the new item is added to the array, but when I return to the table view, the deleted item shows up instead of the new item. The table view seems to be reusing the dequeued cell (not sure).
What am I doing wrong?
CLCheckListViewController.m
#import "CLCheckListViewController.h"
#import "CLTaskFactory.h"
#import "CLTaskStore.h"
#import "CLAddTaskViewController.h"
#implementation CLCheckListViewController
{
__weak IBOutlet UITableView *checkList;
}
- (id)init
{
self = [super init];
if (self) {
// add five sample tasks
CLTaskFactory *task1 = [[CLTaskFactory alloc] init];
[task1 setTaskName:#"Task 1"];
[task1 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task1];
CLTaskFactory *task2 = [[CLTaskFactory alloc] init];
[task2 setTaskName:#"Task 2"];
[task2 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task2];
CLTaskFactory *task3 = [[CLTaskFactory alloc] init];
[task3 setTaskName:#"Task 3"];
[task3 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task3];
CLTaskFactory *task4 = [[CLTaskFactory alloc] init];
[task4 setTaskName:#"Task 4"];
[task4 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task4];
CLTaskFactory *task5 = [[CLTaskFactory alloc] init];
[task5 setTaskName:#"Task 5"];
[task5 setDidComplete:NO];
[[CLTaskStore sharedStore] addTask:task5];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[checkList reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// create edit button
[[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];
// create title
[[self navigationItem] setTitle:#"Checklist"];
// create add guest button
UIBarButtonItem *bbi = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(pushAddTask)];
[[self navigationItem] setRightBarButtonItem:bbi];
}
- (void)pushAddTask
{
CLAddTaskViewController *advk = [[CLAddTaskViewController alloc] init];
[[self navigationController] pushViewController:advk animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[CLTaskStore sharedStore] allTasks] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [checkList dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;
}
return cell;
}
- (void)didCheckTask:(UIButton *)button
{
CGPoint hitPoint = [button convertPoint:CGPointZero toView:checkList];
hitIndex = [checkList indexPathForRowAtPoint:hitPoint];
task = [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[hitIndex row]];
if (task.didComplete) {
task.didComplete = NO;
} else {
task.didComplete = YES;
}
NSInteger taskCount = [[[CLTaskStore sharedStore] allTasks] count];
for (int i = 0; i < taskCount; i++) {
NSLog(#"%#, status: %#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:i], [[[[CLTaskStore sharedStore] allTasks] objectAtIndex:i] didComplete]?#"YES":#"NO");
}
// toggle checkbox
button.selected = !button.selected;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
// set editing mode
if (editing) {
self.navigationItem.title = #"Edit Checklist";
[checkList setEditing:YES];
} else {
self.navigationItem.title = #"Checklist";
[checkList setEditing:NO];
}
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
// remove task
if (editingStyle == UITableViewCellEditingStyleDelete) {
// remove task from CLTaskStore
task = [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]];
[[CLTaskStore sharedStore] removeTask:task];
// remove guest from table view
[checkList deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// reload table view
//[checkList reloadData];
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
[[CLTaskStore sharedStore] moveTaskAtIndex:[sourceIndexPath row] toIndex:[destinationIndexPath row]];
}
#end
CLAddTaskViewController.m
#import "CLAddTaskViewController.h"
#import "CLTaskFactory.h"
#import "CLTaskStore.h"
#implementation CLAddTaskViewController
- (void)viewDidLoad
{
[[self navigationItem] setTitle:#"Add Task"];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// clear first responder
[[self view] endEditing:YES];
// create new task
CLTaskFactory *newTask = [[CLTaskFactory alloc] init];
[newTask setTaskName:[newTaskName text]];
// add new guest to RCGuestStore
[[CLTaskStore sharedStore] addTask:newTask];
}
#end
CLAddTaskFactory.m
#import "CLTaskFactory.h"
#implementation CLTaskFactory
#synthesize taskName;
- (void)setDidComplete:(BOOL)dc
{
didComplete = dc;
}
- (BOOL)didComplete
{
return didComplete;
}
- (NSString *)description
{
// override the description
NSString *descriptionString = [[NSString alloc] initWithFormat:#"%#", taskName];
return descriptionString;
}
#end
CLAddTaskStore.m
#import "CLTaskStore.h"
#import "CLTaskFactory.h"
#import "CLCheckListViewController.h"
#implementation CLTaskStore
+ (id)allocWithZone:(NSZone *)zone
{
return [self sharedStore];
}
+ (CLTaskStore *)sharedStore
{
static CLTaskStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[super allocWithZone:nil] init];
}
return sharedStore;
}
- (id)init
{
self = [super init];
if (self) {
allTasks = [[NSMutableArray alloc] init];
}
return self;
}
- (NSMutableArray *)allTasks
{
return allTasks;
}
- (void)addTask:(CLTaskFactory *)task
{
[allTasks addObject:task];
NSLog(#"Task added: %#", task);
}
- (void)removeTask:(CLTaskFactory *)task
{
// remove the item for the deleted row from the store
[allTasks removeObjectIdenticalTo:task];
NSInteger taskCount = [allTasks count];
NSLog(#"Removed: %#, there are now %d remaining tasks, they are:", task, taskCount);
for (int i = 0; i < taskCount; i++) {
NSLog(#"%#, status: %#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:i], [[[[CLTaskStore sharedStore] allTasks] objectAtIndex:i] didComplete]?#"YES":#"NO");
}
}
- (void)moveTaskAtIndex:(int)from toIndex:(int)to
{
if (from == to) {
return;
}
CLTaskFactory *task = [allTasks objectAtIndex:from];
[allTasks removeObjectAtIndex:from];
[allTasks insertObject:task atIndex:to];
}
#end
Thanks for your help!
The table view seems to be reusing the dequeued cell
That's exactly what it does; it reuses cells whenever possible. If you had enough items to cause the table view to scroll, you'd also see the same problem.
In -tableView:cellForRowAtIndexPath: you must always set up the cell to display the correct content for the given row index, regardless of whether dequeueReusableCellWithIdentifier: returns a cell or not.
Basically:
If -dequeueReusableCellWithIdentifier: returns nil, create a new cell and add your checkbox button to it.
Then set the cell text and the button state on either this new cell or the cell returned from -dequeueReusableCellWithIdentifier:
Darren is correct. If you look at your code here:
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;
}
your only setting up the cell if(cell == nil)
Change your code to
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// put the tasks into the cell
[[cell textLabel] setText:[NSString stringWithFormat:#"%#", [[[CLTaskStore sharedStore] allTasks] objectAtIndex:[indexPath row]]]];
// put the checkbox into the cell's accessory view
UIButton *checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
checkBox = [UIButton buttonWithType:UIButtonTypeCustom];
[checkBox setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[checkBox setImage:[UIImage imageNamed:#"checkbox-checked.png"] forState:UIControlStateSelected];
checkBox.frame = CGRectMake(0, 0, 30, 30);
checkBox.userInteractionEnabled = YES;
[checkBox addTarget:self action:#selector(didCheckTask:) forControlEvents:UIControlEventTouchDown];
cell.accessoryView = checkBox;

Resources