Xcode MultipleCellSelection Selection names - ios

I have a tableview. I want to create string from selected cell names. For example My Cell names : Row No 1 - Row No 2 - Row No 3 - Row No 4 - Row No 5. When selected Row No 1 - Row No 2 - Row No 5 mystring value = Selected Items Row No 1 , Row No 2 , Row No 5. When i deselect Row No 1 mystring value = Selected items Row No 2 , Row No 5 or Row No 5 , Row No 2. It does not matter.
Is it possible? If possible how can i do? Thanks.
//EDIT
My code is here ;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tableData = [[NSMutableArray alloc] init];
[tableData retain];
for (int i=1; i<=10; i++)
{
NSString *rowInString= [[NSString alloc ]initWithFormat:#"Row No %d",i];
[tableData addObject:rowInString];
rowInString=nil;
}
_mytable.allowsMultipleSelectionDuringEditing = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"self.Data count: %lu", (unsigned long)[tableData count]);
return tableData.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];
}
NSString *cellValue;
cellValue=[tableData objectAtIndex:[indexPath row]];
[_mytable setEditing: YES];
cell.textLabel.text=cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *selectedText = #"Selected Items";
NSArray *selectedRows = [_mytable indexPathsForSelectedRows];
NSLog(#"%lu" , (unsigned long)selectedRows.count);
}
- (void)dealloc {
[_mytable release];
[super dealloc];
}
#end

First add in your tableview.
self.myTableView.allowsMultipleSelection = YES;
then
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//you need an array in which you can add and remove strings
//adding the selected row string to array.
[stringArray addObject:[tableData objectAtIndex:[indexPath row]];
NSString *string;
for(NSString *str in stringArray)
{
string = [NSString stringWithFormat:"%#%#",string,str];
}
NSLog(#"Selected Row %#"string);
}
- (void)tableView:(UITableView *)tableView didDeSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//removing the selected string from array
for(NSString *stringInArray in stringArray)
{
if([stringInArray isEqualToString:[tableData objectAtIndex:[indexPath row]])
{
[stringArray removeObject:stringInArray];
}
}
NSString *string;
for(NSString *str in stringArray)
{
string = [NSString stringWithFormat:"%#%#",string,str];
}
NSLog(#"Selected Row %#"string);
}

Here is how you can do it:
Create a NSString *selectedText=#"Selected Items";
Now when you press a item in tableview, didselectitematibdexpath will be called.
Using the indexpath get the cell's name. Now compare if that text exist in the selectedText string. If it exist remove it from string
NSRange check = [selectedText rangeOfString:#" one"];
if (check.location != NSNotFound) {
selectedText = [selectedText stringByReplacingCharactersInRange:check withString:#""];
}
else add it to string using
selectedText=[selectedText stringWithFormat:#" %#",cellName];
Here is your code(i have changed as per your requirement):
NSString *selectedText = #"Selected Items";
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
tableData = [[NSMutableArray alloc] init];
[tableData retain];
for (int i=1; i<=10; i++)
{
NSString *rowInString= [[NSString alloc ]initWithFormat:#"Row No %d",i];
[tableData addObject:rowInString];
rowInString=nil;
}
_mytable.allowsMultipleSelectionDuringEditing = YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"self.Data count: %lu", (unsigned long)[tableData count]);
return tableData.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];
}
NSString *cellValue;
cellValue=[tableData objectAtIndex:[indexPath row]];
[_mytable setEditing: YES];
cell.textLabel.text=cellValue;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSRange check = [selectedText rangeOfString:[tableData objectAtIndex:[indexPath row]]];
if (check.location != NSNotFound) {
selectedText = [selectedText stringByReplacingCharactersInRange:check withString:#""];
} else {
selectedText = [NSString stringwithFormat:#"%# %#",selectedText, [tableData objectAtIndex:[indexPath row]]];
}
NSArray *selectedRows = [_mytable indexPathsForSelectedRows];
NSLog(#"%lu" , (unsigned long)selectedRows.count);
}
- (void)dealloc {
[_mytable release];
[super dealloc];
}
#end

Related

how to get the selected cell values and unselected cell values in uitableview in different array using objective c

pls check the image
i am very new to iOS how to get the selected cell values in one array and unselected cell value in the another array using by using checkmarks in objective c
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
indexofselectedcell = [[NSMutableArray alloc]init];
valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {
[indexofselectedcell addObject:indexPath
customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
NSString *test = cell.balance.text;
[valueofselectedcell addObject:test];
NSLog(#"%# the value of the selected cell value is ",valueofselectedcell);
NSArray *array = [valueofselectedcell copy];
NSNumber* sum = [array valueForKeyPath: #"#sum.self"];
NSLog(#"the sum valuie is .... %#",sum);
NSString *totalamount = [sum stringValue];
_amountlabel.text=totalamount;
NSInteger index = [valueofselectedcell indexOfObject:totalamount];
NSLog(#"%ld the index value in the array is",(long)index);
}}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *totalamount;
if ([indexofselectedcell containsObject: indexPath])
{
NSInteger anIndex=[indexofselectedcell indexOfObject:indexPath];
[indexofselectedcell removeObjectAtIndex:anIndex];
[valueofselectedcell removeObjectAtIndex:anIndex];
NSLog(#"the value of the unselected cell value is..... %#",valueofselectedcell);
NSArray *array = [valueofselectedcell copy];
NSNumber* sum = [array valueForKeyPath: #"#sum.self"];
totalamount = [sum stringValue];
_amountlabel.text=totalamount;
totalamount= nil;
} }
Pavithra I tried sample project for your question and output.If I get unselected and selected cells in separate array,it crashed as I could not check two array in cellForRowAtIndexPath.So that I save selected and unSelected values in one array.
I created simple understandable solution.I have set values in tableview as unselected as default.If you selected(when you click the cell) it shows UITableViewCellAccessoryCheckmark and other show UITableViewCellAccessoryNone.
It works perfectly.You can easily get.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableViewSelectUnSelect;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController (){
NSMutableArray *arrVal,*arrSelectedUnSelectedValues,*arrSelectedValues,*arrUnSelectedValues;
NSMutableArray *arrSubTitle;
}
#end
#implementation ViewController
#synthesize tableViewSelectUnSelect;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrVal= [[NSMutableArray alloc]initWithObjects:#"India",#"China",#"Korea",#"Japan",#"Peru",#"Italy",#"France",#"US",#"Dubai",#"UK",#"Nepal",nil];
arrSubTitle = [[NSMutableArray alloc]initWithObjects:#"100",#"70",#"80",#"90",#"50",#"60",#"70",#"50",#"40",#"30",#"80",nil];
arrSelectedUnSelectedValues= [[NSMutableArray alloc]init];
arrSelectedValues = [[NSMutableArray alloc]init];
arrUnSelectedValues = [[NSMutableArray alloc]init];
for(int j=0;j<[arrVal count];j++)
{
[arrSelectedUnSelectedValues addObject:#"unselected"]; //As Default it is in UnSelected State
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrVal.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:strCell];
}
if([[arrSelectedUnSelectedValues objectAtIndex:indexPath.row] isEqualToString:#"selected"])
cell.accessoryType = UITableViewCellAccessoryCheckmark;
else
cell.accessoryType = UITableViewCellAccessoryNone;
cell.textLabel.text = [arrVal objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [arrSubTitle objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
#try
{
CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewSelectUnSelect];
NSIndexPath *indexPath = [tableViewSelectUnSelect indexPathForRowAtPoint:touchPoint];
NSLog(#"The arrSelectedUnSelectedValues are %#",arrSelectedUnSelectedValues );
NSString *strValue;
if([arrSelectedUnSelectedValues count]==0)
{
for(int i=0; i<[arrVal count]; i++)
{
[arrSelectedUnSelectedValues addObject:#"unselected"];
}
}
if([[arrSelectedUnSelectedValues objectAtIndex:indexPath.row] isEqualToString:#"selected"])
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrSelectedUnSelectedValues replaceObjectAtIndex:indexPath.row withObject:#"unselected"];
strValue = cell.detailTextLabel.text;
[arrUnSelectedValues addObject:strValue];
NSLog(#"The arrUnSelectedValues are - %#",arrUnSelectedValues);
}
else
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[arrSelectedUnSelectedValues replaceObjectAtIndex:indexPath.row withObject:#"selected"];
strValue = cell.detailTextLabel.text;
[arrSelectedValues addObject:strValue];
NSLog(#"The arrSelectedValues - %#",arrSelectedValues);
}
}
#catch (NSException *exception) {
NSLog(#"The exception is-%#",exception);
}
}
#end
First when I run the application it shows like below
Then when I select values from the tableView
Then finally printed results are

UItableView load data on scroll in ios

Hi in my array there is huge amount of data and I have to display it in UITableView. But the condition here is I have to display only 5 records initially,then once the user scroll down I have to load more records.I tried searching it but didn't get any useful answer please help me and I agree that we have to use ((void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath )
Another way
we can adjust the return value of tableView:numberOfRowsInSection: method, every time we want to insert ten rows, you can plus 5 to the return value.
but i am not understand how to do this please help me
my code:
#import "TableViewController.h"
#interface TableViewController ()
{
UITableView * tableView;
NSUInteger reloads_;
NSMutableArray * MainArray;
int scrollValue;
long dataLimit;
NSArray * yourDataSource;
}
#end
#implementation TableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
MainArray = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10",nil];
tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tableView.delegate = self;
tableView.dataSource = self;
tableView.backgroundColor = [UIColor clearColor];
[self.view addSubview:tableView];
}
#pragma mark - UITableViewDataSource
// number of section(s), now I assume there is only 1 section
- (NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView
{
return 1;
}
// number of row in the section, I assume there is only 1 row
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return yourDataSource.count;
}
// the cell will be returned to the tableView
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [yourDataSource objectAtIndex:indexPath.row];
return cell;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
[self estimatedTotalData];
}
- (void)estimatedTotalData
{
long currentRow = ((NSIndexPath *)[[tableView indexPathsForVisibleRows] lastObject]).row;
// 25 here is the initial data count
long estimateDataCount = 25;
while (currentRow > estimateDataCount)
{
estimateDataCount+=25;
}
dataLimit = estimateDataCount;
if (dataLimit == currentRow+1)
{
dataLimit+=25;
if (dataLimit != estimateDataCount)
{
//[self requestForData]; or load necessary data
// take not that dataLimit is the total data that must be displayed.
NSArray *yourLocalData = #[#"1", #"2", #"3", #"4", #"5"];
// just add more sample objects
yourDataSource = [self setsLimitForObject: yourLocalData limit: dataLimit];
[tableView reloadData];
}
}
}
- (NSArray *)setsLimitForObject:(id)object limit:(long)limit
{
if ([object isKindOfClass:[NSArray class]])
{
NSMutableArray *tempArray = [object mutableCopy];
NSRange range = NSMakeRange(0, limit);
if (tempArray.count >= range.length)
return [tempArray subarrayWithRange:range];
else
{
NSLog(#"Out of bounds");
return object;
}
} else NSLog(#"Sets Log: Cannot set limit for object %#", [object class]);
return nil;
}
#end
Try this approach, this is more like a paging...
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
[self estimatedTotalData];
}
- (void)estimatedTotalData
{
long currentRow = ((NSIndexPath *)[[YourTableView indexPathsForVisibleRows] lastObject]).row;
// 25 here is the initial data count
long estimateDataCount = 25;
while (currentRow > estimateDataCount)
{
estimateDataCount+=25;
}
dataLimit = estimateDataCount;
if (dataLimit == currentRow+1)
{
dataLimit+=25;
if (dataLimit != estimateDataCount)
{
//[self requestForData]; or load necessary data
// take not that dataLimit is the total data that must be displayed.
NSArray *yourLocalData = #[#"1", #"2", #"3", #"4", #"5"];
// just add more sample objects
yourDataSource = [self setsLimitForObject: yourLocalData limit: dataLimit];
[yourTable reloadData];
}
}
}
Update:
- (NSArray *)setsLimitForObject:(id)object limit:(long)limit
{
if ([object isKindOfClass:[NSArray class]])
{
NSMutableArray *tempArray = [object mutableCopy];
NSRange range = NSMakeRange(0, limit);
if (tempArray.count >= range.length)
return [tempArray subarrayWithRange:range];
else
{
NSLog(#"Out of bounds");
return object;
}
} else NSLog(#"Sets Log: Cannot set limit for object %#", [object class]);
return nil;
}
You can use below code for your cellForRowAtIndexPath,
- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [mainArray objectAtIndex:indexPath.row];
if (indexPath.row % 5 == 0) { // this if loop will get execute at every fifth row
// if you are loading data from API response then call API here and add next set of data into your existing array.
// then just reload your tableview by it's name e.g. [theTableView reloadData];
}
return cell;
}
and for your numberOfRowsInSection, instead of fixed 5 rows, just use mainArray.count like below,
- (NSInteger)tableView:(UITableView *)theTableView numberOfRowsInSection:(NSInteger)section
{
return mainArray.count;
}

How to move row to another Section while clicking on row?

I have Implemented multi select row but what i have to do is when we click on row it will move on another section , Here's my code what i have tried is ?
can anyone help me out from this ? Thanks in advance ...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2; //assuming you have only two sections
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return self.firstSectionDataSource.count;
else if (section == 1)
return self.dataArray.count;
else
return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Here, Have to move row to another section while clcking ..
// other multiselect code
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure a cell to show the corresponding string from the array.
static NSString *kCellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
#try {
NSMutableArray *sourceArray = nil;
if (sourceIndexPath.section == 0) {
sourceArray = self.firstSectionDataSource;
}
else if (sourceIndexPath.section == 1)
{
sourceArray = self.dataArray;
}
NSMutableArray *destinationArray = nil;
if (destinationIndexPath.section == 0) {
destinationArray = self.firstSectionDataSource;
}
else if (destinationIndexPath.section == 1)
{
destinationArray = self.dataArray;
}
NSString *stringToMov = [sourceArray objectAtIndex:sourceIndexPath.row];
[sourceArray removeObject:stringToMov];
[destinationArray insertObject:stringToMov atIndex:destinationIndexPath.row];
}
#catch (NSException *exception) {
NSLog(#"exception = %# \n reason = %#",exception,exception.reason);
}
}
In cellForRowAtIndexPath
[cell setShowsReorderControl:YES];
And you need to implement the following UITableView delegate and data source methods properly
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 2; //assuming you have only two sections
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
return firstSectionDataSource.count;
else if (section == 1)
return secondSectionDataSource.count;
else
return 0;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
#try {
NSMutableArray *sourceArray = nil;
if (sourceIndexPath.section == 0) {
sourceArray = firstSectionDataSource;
}
else if (sourceIndexPath.section == 1)
{
sourceArray = secondSectionDataSource;
}
NSMutableArray *destinationArray = nil;
if (destinationIndexPath.section == 0) {
destinationArray = firstSectionDataSource;
}
else if (destinationIndexPath.section == 1)
{
destinationArray = secondSectionDataSource;
}
NSString *stringToMov = [[sourceArray objectAtIndex:sourceIndexPath.row] retain];
[sourceArray removeObject:stringToMov];
[destinationArray insertObject:stringToMov atIndex:destinationIndexPath.row];
[stringToMov release];
}
#catch (NSException *exception) {
NSLog(#"exception = %# \n reason = %#",exception,exception.reason);
}
}
You can do the next:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView moveRowAtIndexPath:indexPath toIndexPath:[NSIndexPath indexPathForRow:row inSection:section]];
// other multiselect code
}
Try this -
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObjects:[NSArray arrayWithObjects:#"a",#"b",#"c", nil],[NSArray arrayWithObjects:#"d",#"e",#"f", nil], nil] forKeys:[NSArray arrayWithObjects:#"firstSection",#"secondsection", nil]];
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[dict allKeys] count]; //assuming you have only two sections
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[dict objectForKey:[dict allKeys][section]] count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *arr = [dict objectForKey:[dict allKeys][indexPath.section]];
NSString *str = arr[indexPath.row];
if (indexPath.row!=0) {
[arr removeObject:str];
}
NSMutableArray *arr1 = [dict objectForKey:[dict allKeys][0]];
[arr1 addObject:str];
[tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray *arr = [dict objectForKey:[dict allKeys][indexPath.section]];
NSString *str = arr[indexPath.row];
static NSString *kCellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellID];
cell.textLabel.text = str;
return cell;
}

How to manage multiple cell selection of UITableView using single NSArray?

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.

Selecting Cell in Table IOS

I am trying to create a method that changes the string object "tableColorName" to the cell selected. The tableData NSArray consists of object: "red","blue","green". I want to save the string "tableColorName" to redColor if red is selected, blueColor if blue, greenColor if green. After the cell is selected I want the viewController to go back to the root. I appreciate your help in advance:
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int theRow = indexPath.row;
NSString *tableColorName;
tableColorName = [[NSString alloc] initWithString:([_tableData [theRow] stringValue],#"Color")];
[self.navigationController popToRootViewControllerAnimated:YES];
}
//first of all take one NSArray and
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.colorNames = [[NSArray alloc] initWithObjects:#"Red", #"Green",
#"Blue", #"Indigo", #"Violet", nil];
}
// Implement Table method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.colorNames count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
self.navigationItem.title=#"Colors";
UIImage *cellImage = [UIImage imageNamed:#"a.png"];
cell.imageView.image = cellImage;
NSString *colorString = [self.colorNames objectAtIndex: [indexPath row]];
cell.textLabel.text = colorString;
NSString *subtitle = [NSString stringWithString: #"All about the color "];
subtitle = [subtitle stringByAppendingFormat:colorString];
cell.detailTextLabel.text = subtitle;
return cell;
}
- (void)tableView: (UITableView *)tableView didSelectRowAtIndexPath: (NSIndexPath *)indexPath
{
int idx = indexPath.row;
obj.lbl.text=[#"You select "stringByAppendingString:[colorNames objectAtIndex:idx]];
[self popToViewController animated:YES];
}
Try this ::
NSArray *arr;
NSString *tableColorName; // Use in AppDelegate
- (void)viewDidLoad
{
arr = [[NSArray alloc] initWithObjects:#"Red", #"Green", #"Blue", nil];
}
Table View Methods ::
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.title.text = [NSString stringWithFormat:#"%#", [arr objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
app.tableColorName = [NSString StringWithFormat:#"%# Color", [arr objectAtIndex:indexPath.row]];
[self.navigationController popToRootViewControllerAnimated:YES];
}
Then, access by app.tableColorName whenever you want to display.
Thanks.
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
//do whatever with the selected cell.
//go back to the root
}

Resources