I'm asking the user to select options in a UITableView and then saving the selection in NSUserDefaults. I'm making sure that if the user selects an option twice, it gets added only once..i.e no duplicates.
I'm loading the NSUserDefaults and then trying to show the rows as "checked"..so that the user remembers what he/she had selected when they had run the app earlier.
Now, I know that only the cellForRowAtIndexPath method can set a checkmark.
The below code only checkmarks the last object. But how do I get multiple checkmarks?
This is how far I've gotten.
- (void)viewDidLoad {
[super viewDidLoad];
appSettings = [NSUserDefaults standardUserDefaults];
self.title = #"Select News Categories";
_selectedCategoriesArray = [[NSMutableArray alloc] init];
[self initNewsCategories];
[self loadNewsSelectedCategories];
}
#pragma mark UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_newsCategoriesArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cellNewsCategory" forIndexPath:indexPath];
// Configure the cell...
cell.textLabel.text = [NSString stringWithFormat:#"%#",[_newsCategoriesArray objectAtIndex:indexPath.row]];
NSString * cellText = [[cell textLabel] text];
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
return cell;
}
#pragma mark UITableViewDelegate methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell * selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString * selectedCategory = [[selectedCell textLabel] text];
if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone)
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark];
NSLog(#"%#", selectedCategory);
[_selectedCategoriesArray addObject:selectedCategory];
NSLog(#"_selectedCategoriesArray:%#", _selectedCategoriesArray);
[appSettings setObject:_selectedCategoriesArray forKey:#"selectedNewsCategories"];
}
else if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
NSLog(#"%#", selectedCategory);
[_selectedCategoriesArray removeObject:selectedCategory];
NSLog(#"_selectedCategoriesArray:%#", _selectedCategoriesArray);
[appSettings setObject:_selectedCategoriesArray forKey:#"selectedNewsCategories"];
}
else
{
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone];
}
[appSettings synchronize];
}
#pragma mark Helper methods
-(void) initNewsCategories
{
_newsCategoriesArray = [NSArray arrayWithObjects:#"Arts",#"Business",#"Company",
#"Entertainment",#"Environment",#"Health",#"Lifestyle",
#"Media",#"Money",#"Most Read",#"Trending",#"World",nil];
}
-(void) loadNewsSelectedCategories
{
_selectedNewsCategories = [[NSMutableArray alloc] init];
_selectedNewsCategories = [appSettings objectForKey:#"selectedNewsCategories"];
}
You have a problem in this code:
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
You first checkmark cell but then you continue search and unmark cell.
You need to use this:
for (NSString * lbl in _selectedNewsCategories)
{
if ([cellText isEqualToString:lbl])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
break;
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
}
Or this
if([_selectedNewsCategories indexOfObject: cellText] != NSNotFound)
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
Related
I have made one sample demo.
Like selected cell print after "Done"button clicked.
It is working fine.
Code is
#synthesize arrayContainer,filteredRecipes,myTableView,filtered,selectedRaw;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.arrayContainer = [[NSMutableArray alloc]initWithObjects:#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine", nil];
self.selectedRaw = [[NSMutableArray alloc]init];
}
-(IBAction)printSelectedItem:(id)sender
{
NSLog(#"The Selected Items are %#",self.selectedRaw);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(filtered == YES)
{
return self.filteredRecipes.count;
}
else
{
return self.arrayContainer.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"myCell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];
if(filtered == YES)
{
cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// NSString *string = [self.selectedRaw objectAtIndex:indexPath.row];
[self.selectedRaw removeObjectAtIndex:indexPath.row];
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row];
[self.selectedRaw addObject:temp];
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
[searchBar setShowsCancelButton:YES animated:YES];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
if([searchText length] == 0)
{
self.filtered = NO;
}
else
{
self.filtered = YES;
self.filteredRecipes = [[NSArray alloc]init];
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#",searchText];
filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate];
}
[self.myTableView reloadData];
}
Question is
-> When I print selected row of table view ,Displayed in log perfectly.
-> But when I deselected those selected item it gives me n error.
Please give me solution.
My another question is when I have searched particular item (selected) it gives me selected item perfectly,then i deselect item after I have canceled searching then it gives me again selected item which I did deselect earlier.
Output image
selected Raw
Unchecked second raw
So please try this.
#import "SecondViewController.h"
#interface SecondViewController ()
#property(nonatomic,strong)NSArray *arrayContainer;
#property(nonatomic,strong)NSArray *filteredRecipes;
#property(nonatomic,strong)NSMutableArray *selectedRaw;
#property(nonatomic,assign)BOOL filtered;
#end
#implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
_arrayContainer = #[#"One",#"Two",#"Three",#"Four"];
// _arrayContainer = [[NSMutableArray alloc]initWithArray:];
_selectedRaw = [[NSMutableArray alloc]init];
[self.tableView reloadData];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if(_filtered)
return _filteredRecipes.count;
else
return _arrayContainer.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
if(_filtered){
NSString *tmp = [_filteredRecipes objectAtIndex:indexPath.row];
cell.textLabel.text = tmp;
if([_selectedRaw containsObject:tmp])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
}else{
NSString *tmp = [_arrayContainer objectAtIndex:indexPath.row];
cell.textLabel.text = tmp;
if([_selectedRaw containsObject:tmp])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
if(self.filtered){
if([self.selectedRaw containsObject:[self.filteredRecipes objectAtIndex:indexPath.row]]){
[self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.filteredRecipes objectAtIndex:indexPath.row]]];
}else{
NSString *temp = [self.filteredRecipes objectAtIndex:indexPath.row];
[self.selectedRaw addObject:temp];
}
}else{
if([self.selectedRaw containsObject:[self.arrayContainer objectAtIndex:indexPath.row]]){
[self.selectedRaw removeObjectAtIndex:[self.selectedRaw indexOfObject:[self.arrayContainer objectAtIndex:indexPath.row]]];
}else{
NSString *temp = [self.arrayContainer objectAtIndex:indexPath.row];
[self.selectedRaw addObject:temp];
}
}
[self.tableView reloadData];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if([searchText length] == 0)
{
self.filtered = NO;
}
else
{
self.filtered = YES;
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#",searchText];
_filteredRecipes = [self.arrayContainer filteredArrayUsingPredicate:resultPredicate];
}
[self.tableView reloadData];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
_filtered = !_filtered;
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
_filtered = !_filtered;
}
#end
You have to remove data based on Object not based on Index so here you can go with below code:
1st you have to check filter condition in your didselect method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(filtered == YES)
{
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedRaw removeObject:[self.filteredRecipes objectAtIndex:indexPath.row]];
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedRaw addObject:[self.filteredRecipes objectAtIndex:indexPath.row]]
}
}
else
{
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
[self.selectedRaw removeObject:[self.arrayContainer objectAtIndex:indexPath.row]];
} else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[self.selectedRaw addObject:[self.arrayContainer objectAtIndex:indexPath.row]]
}
}
}
2nd Problem solution:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"myCell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:identifier];
if(filtered == YES)
{
cell.textLabel.text = [self.filteredRecipes objectAtIndex:indexPath.row];
if([selectedRaw containsObject:self.filteredRecipes[indexPath.row]] ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
else
{
cell.textLabel.text = [self.arrayContainer objectAtIndex:indexPath.row];
if([selectedRaw containsObject:self.arrayContainer[indexPath.row]] ){
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}else{
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
return cell;
}
Hope This will helps you.
1: You have to take array with dictionary with parameter like
[{
value : “One”,
state : “Check”
},
{
value : “Two”,
state : “UnCheck”
}
]
then on cellForRowAtindexParth
if (self.selectedRaw[indexPath.row] as ! NSDictionary).value(forKey:”state”) as! String == “Check”{
//change to check mark
}
else{
//change to UnCheck mark
}
At DidSelectRowAtIndexPath
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
if (arr[indexPath.row] as ! NSDictionary).value(forKey:”state”) as! String == “Check”{
//change state value to UnCheck
}else{
//change state value to Check
}
}
2:On second point you need to do same work
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!
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];
}