This question already has an answer here:
TableView Cell reuse and unwanted checkmarks - this is killing me
(1 answer)
Closed 9 years ago.
I'm trying to set checkmark in rows which are selected in UITableView (placed in popup view). Actually I have something like this:
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Check if current row is selected
Boolean isNowChecked = NO;
if([self.tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)
{
isNowChecked = YES;
}
if(isNowChecked)
{
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
}
else
{
[self.tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
}
return indexPath;
}
In result I'm able to select rows, for example I touch first item then I see checkmark. When I scroll down my table view, then I see that I have check also other items (number 17, 32). When I uncheck my first item, then every check also disappear.
Do you have any suggestions what could be reason of this situation, and how can I avoid it?
// Try this
//in .h
NSMutableArray *arr_fortable;
//in .m
- (void)viewDidLoad
{
[super viewDidLoad];
arr_fortable = [[NSMutableArray alloc] init];
for (int i =0; i<5; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithFormat:#"%d",i+1] forKey:#"data"];
[dict setObject:#"0" forKey:#"checkmark"];
[arr_fortable addObject:dict];
}
}
- (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 [arr_fortable count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [[arr_fortable objectAtIndex:indexPath.row] objectForKey:#"data"];
if ([[[arr_fortable objectAtIndex:indexPath.row] objectForKey:#"checkmark"] integerValue] == 1)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[[arr_fortable objectAtIndex:indexPath.row] objectForKey:#"checkmark"] integerValue] == 1)
{
[[arr_fortable objectAtIndex:indexPath.row] setObject:#"0" forKey:#"checkmark"];
}
else
{
[[arr_fortable objectAtIndex:indexPath.row] setObject:#"1" forKey:#"checkmark"];
}
[self.tableView reloadData];
}
see this..
tableView:didSelectRowAtIndexPath: and update which data is checked in tableView:cellForRowAtIndexPath: like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// do usual stuff here including getting the cell
// determine the data from the IndexPath.row
if (data == self.checkedData)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// determine the selected data from the IndexPath.row
if (data != self.checkedData) {
self.checkedData = data;
}
[tableView reloadData];
}
Related
i tried like this...in cellForRowAtIndex()
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableViewIdentifier=#"SimpleTableViewIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SimpleTableViewIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableViewIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text=[hardDependencyAlldataArray objectAtIndex:indexPath.row];
return cell;
}
and added below lines of code in didSelectRowAtIndexPath..
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
but,while updating the previous selected value,check mark is not showing onpreviously selected rows..any one can help in this issue..Thanks in advance.. :)
I think this is what you need to do. In your cellForRowAtIndexPath method, instead of assigning cell.selectionStyle = UITableViewCellSelectionStyleNone; for all cells, assign it to none only for those cells which are not selected
Change the didSelectRowAtIndexPath method to store the selected cell detail to an array
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedCellArray addObject:[hardDependencyAlldataArray objectAtIndex:indexPath.row]];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Now change the cellForRowAtIndexPath method like this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableViewIdentifier=#"SimpleTableViewIdentifier";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:SimpleTableViewIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableViewIdentifier];
}
cell.textLabel.text=[hardDependencyAlldataArray objectAtIndex:indexPath.row];
if (![self.selectedCellArray containsObject:[hardDependencyAlldataArray objectAtIndex:indexPath.row]])
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
return cell;
}
I got it Tamim. Check the below answer.I tried sample project.It works fine.
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrProductSelection,*arrProductSelectDeSelectCheckMark;
NSArray *arrayFetchFromDefaults;
NSInteger lastSelectedIndex;
}
#end
#implementation ViewController
#synthesize tableViewCheckMarkSelectionUpdate;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
arrProductSelection = [[NSMutableArray alloc]initWithObjects:#"iPhone",#"iPad",#"iPod",#"iTV",#"iWatch",#"iMac",nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
[NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
arrayFetchFromDefaults = [userDefaults objectForKey:#"selectedcheckmark"];
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
if(arrProductSelectDeSelectCheckMark.count == 0)
{
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
for(int j=0;j<[arrProductSelection count];j++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
[tableViewCheckMarkSelectionUpdate reloadData];
}
#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrProductSelection.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
// lastSelectedIndex = [[NSUserDefaults standardUserDefaults] integerForKey:#"selectedRow"]; - Getting Last selected index row
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
cell.accessoryType = UITableViewCellAccessoryNone;
else
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// if (indexPath.row == lastSelectedIndex)
// cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.textLabel.text = [arrProductSelection objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// [[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:#"selectedRow"]; //This is for Last Selected IndexPath Row
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
#try
{
CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewCheckMarkSelectionUpdate];
NSIndexPath *indexPath = [tableViewCheckMarkSelectionUpdate indexPathForRowAtPoint:touchPoint];
NSLog(#"%#",arrProductSelectDeSelectCheckMark);
if([arrProductSelectDeSelectCheckMark count]==0)
{
for(int i=0; i<[arrProductSelection count]; i++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"selected"];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"deselected"];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrProductSelectDeSelectCheckMark forKey:#"selectedcheckmark"];
[defaults synchronize];
}
#catch (NSException *exception) {
NSLog(#"The exception is-%#",exception);
}
}
- (IBAction)actionGoPrevious:(id)sender
{
[self.navigationController popToRootViewControllerAnimated:YES];
}
#end
Here is my code which handles multiple selection of UITableview Cell properly.
Now, my question is here I had create two array in which one stores array data and second stores selected data. But, I want to do this using only one array. someone had given me solution that it can be done using KVC (valueForKeyPath) by giving key. But I have no exact idea how to do it.
If anyone knows please help me.
#import "NewTableViewController.h"
#implementation NewTableViewController
#synthesize attTableData ;
#synthesize arrSelectionData ;
- (void)viewDidLoad
{
[super viewDidLoad];
self.attTableData=[NSArray arrayWithObjects:#"Dhosa",#"Kahman",#"Dhokla",#"Handvo",#"chodafadi",#"Muthiya",#"Medu Vada",#"Patra",#"Thepla",#"Fafda",#"Gota",#"gathiya",#"Idali",#"Dalvada",#"Samosa",nil];
self.arrSelectionData=[NSMutableArray array];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.attTableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
if([self.arrSelectionData containsObject:indexPath])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
cell.textLabel.text=[self.attTableData objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arrSelectionData containsObject:indexPath])
{
[self.arrSelectionData removeObject:indexPath];
}
else
{
[self.arrSelectionData addObject:indexPath];
}
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//[tableView reloadData];
}
#end
Solution ::
Data in "Recipe List" File
[0]{
Item = Thepla;
selected = 0;
},
[1]
{
Item = Gota;
selected = 0;
},
[2]
{
Item = Handvo;
selected = 0;
},
[3]
{
Item = Idali;
selected = 0;
},
[4]
{
Item = Dalvada;
selected = 0;
},
Now My TableViewController
#import "NewTableViewController.h"
#import "TableViewCell.h"
#implementation NewTableViewController
#synthesize attTableData ;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Recipe List" ofType:#"plist"];
attTableData = [[NSMutableArray alloc]initWithContentsOfFile:path];
attTableData = (NSMutableArray *)CFBridgingRelease(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFArrayRef)attTableData, kCFPropertyListMutableContainers));
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.attTableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"UserCell";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
NSDictionary * dicTemp = [attTableData objectAtIndex:indexPath.row];
// NSNumber* attendingObject = [dicTemp objectForKey:#"selected"];
if([dicTemp objectForKey:#"selected"] == [NSNumber numberWithBool:NO])
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
cell.lbl.text=[[self.attTableData objectAtIndex:indexPath.row]objectForKey:#"Item"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSMutableDictionary * dic = [attTableData objectAtIndex:indexPath.row];
//NSNumber* attendingObject = [dic objectForKey:#"selected"];
if ([dic objectForKey:#"selected"] == [NSNumber numberWithBool:NO])
{
[dic setValue:[NSNumber numberWithBool:YES] forKey:#"selected"];
}
else
{
[dic setValue:[NSNumber numberWithBool:NO] forKey:#"selected"];
}
[attTableData replaceObjectAtIndex:indexPath.row withObject:dic];
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
#end
If you want to do it using a single array, instead of doing like this
self.attTableData=[NSArray arrayWithObjects:#"Dhosa",#"Kahman",#"Dhokla",#"Handvo",#"chodafadi",#"Muthiya",#"Medu Vada",#"Patra",#"Thepla",#"Fafda",#"Gota",#"gathiya",#"Idali",#"Dalvada",#"Samosa",nil];
Create a model class for your items
//pseudo code
class Item{
name = "Dhosa"
selected = false
}
So attTableData will be
self.attTableData=[Item1, Item2];
Now when you make a selection you can set the selected property of the item. In cellForRow check this property and set setAccessoryType.
i need to add checkmark when we tap on each cell, and it must show when i return back to tableview.
I tried with this code but its not working,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if (self.thread == nil) {
cell.textLabel.text = #"Loading, please wait...";
} else if ([self.thread count] == 0) {
cell.textLabel.text = #"No Results!";
} else {
//
NSDictionary *msg = [self.thread objectAtIndex:indexPath.row];
NSLog(#"yourMutableDictionary - %#",msg);
if (indexPath.row == 0) {
cell.textLabel.text = [thread objectAtIndex:0];
} else {
cell.textLabel.text = [NSString stringWithFormat:#"%# ", [msg objectForKey:#"id"]];
if ([self.idSelected count] != 0) {
if ([self.idSelected containsObject:[NSString stringWithFormat:#"%#", [msg objectForKey:#"id"]]]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
}
}
}
return cell;
}
#pragma mark - Table view delegate
//In a xib-based application, navigation from a table can be handled in - tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)path
{
if (self.thread == nil || self.thread.count == 0) {
return;
}
UITableViewCell *cell = [tableView cellForRowAtIndexPath:path];
if (path.row == 0) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;// this checkmark not working
}
else {
NSDictionary *user = [self.thread objectAtIndex:path.row];
NSString *uName = [NSString stringWithFormat:#"%# %#", [user objectForKey:#"first_name"], [user objectForKey:#"last_name"]];
NSString *uId = [NSString stringWithFormat:#"%#",[user objectForKey:#"id"]];
NSLog(#" click id%#", uId);
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
[userNames removeObject:uName];
[userIds removeObject:uId ];
cell.accessoryType = UITableViewCellAccessoryNone; // this check mark is working perfectly
} else {
[userNames addObject:uName];
[userIds addObject:uId];
cell.accessoryType = UITableViewCellAccessoryCheckmark; // this check mark is working perfectly
}
}
}
first cell check mark is not working but others working perfectly. I want to add check mark on first cell too, how its possible
Use below code to display checkmark on multiple table view cell :
- (void)viewDidLoad
{
[super viewDidLoad];
self.arraySelectedCell = [NSMutableArray array];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([self.arraySelectedCell containsObject:indexPath])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
// do here..
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//the below code will allow multiple selection
if ([self.arraySelectedCell containsObject:indexPath])
{
[self.arraySelectedCell removeObject:indexPath];
}
else
{
[self.arraySelectedCell addObject:indexPath];
}
[tableView reloadData];
}
happy coding!
So I've implemented a UIViewController with a tableview, and basically it loads as a set of "filters" for my uicollectionview.
Now, when I click on the checkmarks in my tableview, it "filters" my cells accordingly, but now when I reload the view again I want to display the most recent "checkmarks" I've used, or "filters."
I have seen this being implemented with NSUserDefaults, but I have not been able to successfully implement this.
If anyone could help me, that will be greatly appreciated.
CODE
FiltersViewController.m:
#import "FiltersViewController.h"
#interface FiltersViewController ()
#property (nonatomic, strong) NSMutableSet *selectedRowObjects;
//#property (nonatomic, strong) NSArray *filters;
#end
#implementation FiltersViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.selectedRowObjects = [NSMutableSet setWithCapacity:10];
}
- (IBAction)filtersSelected:(id)sender {
[self.delegate filtersSelected:self.selectedRowObjects];
}
- (IBAction)cancelFilterSelection:(id)sender {
[self.delegate filterSelectionCancelled];
}
- (NSString *)getKeyForIndex:(int)index
{
return [NSString stringWithFormat:#"KEY%d",index];
}
- (BOOL) getCheckedForIndex:(int)index
{
if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES)
{
return YES;
}
else
{
return NO;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"filter" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%u", indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *obj = cell.textLabel.text;
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedRowObjects removeObject:obj];
}
else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedRowObjects addObject:obj];
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
you need to check in cellForRowAtIndexPath also. Write this code in this
if([[NSUserDefaults standardUserDefaults] objectForKey:[self getKeyForIndex:indexPath.row]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
And yes don't forget to call this method in didSelectRowAtIndexPath
[self checkedCellAtIndex:indexPath.row];
Enjoy.
You did almost everything right. You just need to put your logic for reading the NSUserDefault values (for the checked boxes) in the cellForRowAtIndexPath delegate method. That is the method that draws the UITableViewCells when they are displayed on screen. Something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"filter" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%u", indexPath.row];
if ([self getCheckedForIndex:indexPath.row])
{
//code to set checkbox
}
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *simpleTableIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = ArrayOfObject[indexPath.row];
NSUserDefaults *ud =[NSUserDefaults standardUserDefaults];
if([[ud objectForKey:#"selectedObjectKey "]isEqualToString:ArrayOfObject[indexPath.row]])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
You have implemented perfectly. You just need to modify you cellForRowAtIndexPath Method
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"filter" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%u", indexPath.row];
BOOL checked = [self getCheckedForIndex:indexPath.row];
if(checked)
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
Also Call [self checkedCellAtIndex:indexPath.row]; from didSelectRowAtIndexPath method of UITableView.
The best way to save tableView CheckMark with NSUserDefaults
#interface TableViewController (){
NSArray *TableTitles;
NSMutableArray *SelectedRows;
}
viewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
// table view array
TableTitles = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10", nil];
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
SelectedRows = [NSMutableArray arrayWithArray:[userDef objectForKey:#"SelectedRows"]];
}
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = TableTitles[indexPath.row];
NSNumber *obj = [NSNumber numberWithInteger:indexPath.row];
if ([SelectedRows containsObject:obj])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
didSelectRowAtIndexPath
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSNumber *obj = [NSNumber numberWithInteger:indexPath.row];
if ([SelectedRows containsObject:obj])
{
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
[SelectedRows removeObject:obj];
[tableView reloadData];
}else{
[tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
[SelectedRows addObject:obj];
[tableView reloadData];
}
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
[userDef setObject:SelectedRows forKey:#"SelectedRows"];
[userDef synchronize];
}
updated ...
i updated all code with a new way , it's the best way to save TableView CheckMarks and it's now easy and efficient, now only one array is used for saving and loading , code reduced too much :)
You should load data in NSUserDefaults while call cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"filter" forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:#"%u", indexPath.row];
//You should set accessoryType here by NSUserDefaults data
if ([self getCheckedForIndex:indexPath.row]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
I think what you are looking for is to get the current state of the table for the filters when you enter and exit the view. You need to utilize the - (void)viewWillDisappear:(BOOL)animated to save the current state of the table to your NSUserDefaults, and then use - (void)viewDidLoad and - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath to set the checkmark when the table reloads.
#interface FiltersViewController () {
NSMutableArray *_filterStates;
}
#end
- (void)viewDidLoad {
filterStates = [[NSMutableArray alloc] init];
// get state of your current filters in NSUserDefaults, these should be stored as [NSNumber numberWithBool:]
}
- (void)viewWillDisappear:(BOOL)animated {
// store all of your filters into your NSUserDefaults as [NSNumber numberWithBool:]
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// get your cell from the table
BOOL isChecked = [[_filterStates objectAtIndex:indexPath.row] boolValue];
// set the checkmark based on the current state for this filter
}
I am trying to save the checkmark that i place on a cell and then retrieve it. I have 11 cells in that section.
I tried to use this link as a guide and it works. But i want only need one checkmark to be saved rather than many.
And also i want to set checkmark for all cells by default. How would i achieve this
My Code :
- (NSString *)getKeyForIndex:(int)index{
return [NSString stringWithFormat:#"KEY%d",index];
}
- (BOOL) getCheckedForIndex:(int)index {
if([[[NSUserDefaults standardUserDefaults] valueForKey:[self getKeyForIndex:index]] boolValue]==YES) {
return YES;
}
else
{
return NO;
}
}
- (void) checkedCellAtIndex:(int)index
{
BOOL boolChecked = [self getCheckedForIndex:index];
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithBool:!boolChecked] forKey:[self getKeyForIndex:index]];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if(section == 4) {
if([self getCheckedForIndex:indexPath.row]==YES) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = nil;
NSString *key = [_keys objectAtIndex:indexPath.section];
NSArray *name = [_names objectForKey:key];
static NSString *MyCellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyCellIdentifier];
cell.textLabel.text = [name objectAtIndex:indexPath.row];
if(section == 4) {
[self checkedCellAtIndex:indexPath.row];
if([self getCheckedForIndex:indexPath.row]==YES)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
Solution can be tricky :
Maintain one array same to tableview datasource array.
Say for example u have NSMutableArray *mutArrNames which tableview datasource. Now NSMutableArray *mutArrNamesCheckListwhich shows which one is checked or not;
Intially nothing is selected so add 0 to uncheck one:
for(int i =0; i<[mutArrNames count];i++)
{
[mutArrNamesCheckList addObject:#"0"];
}
Now use like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
if(section == 4) {
//check from mutArrNamesCheckList's list if cell is check one or not
if([[mutArrNamesCheckList objectAtIndex:indexPath.row] intValue] == 1) //checked one
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else //unchecked one
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
}
return cell;
}
Here it can be used according to your requirement like allow mutiple selection or single selection.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//get cell object
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(section == 4)
{
if([[mutArrNamesCheckList objectAtIndex:indexPath.row] intValue] == 1) //checked one
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
//replace 0 with 1 as check one
[mutArrNamesCheckList replaceObjectAtIndex:indexPath.row withObject:#"0"];
}
else //unchecked one
{
cell.accessoryType = UITableViewCellAccessoryNone;
//replace 1 with 0 as uncheck one
[mutArrNamesCheckList replaceObjectAtIndex:indexPath.row withObject:#"1"];
}
}
}
For selection and unselection of all cell add this in button's action method. Use this :
//remove all as new objects will be added
[mutArrNamesCheckList removeAllObjects];
if(!btnCheckAll.selected)//selected property used - default is no so all not selected
{
//make all selected
for(int i =0; i<[mutArrNames count];i++)
{
[mutArrNamesCheckList addObject:#"1"];
}
//change buttons image here
}
else
{
//make all unselected
for(int i =0; i<[mutArrNames count];i++)
{
[mutArrNamesCheckList addObject:#"0"];
}
//change buttons image here
}
//tableView reload
[yourtableView reloadData];
btnCheckAll.selected = !btnCheckAll.selected;
Add mutArrNamesCheckList in AppDelegate to be visible in whole Application.
So remove iteration we done on top of above answer in our viewcontroller as we didn't wanted to use gobally
EDIT : added toggling in didSelectRowAtIndexPath + clicked select all button, all cell is checked else unchecked