UITableViewCell is not in the right order after creating - ios

I have to create an UITableView that contains 2 custom cells RestTime and ExerciseTime. That after an ExerciseTime is a RestTime cell.
Here is the design of my tableView:
And here is my implement code:
-Cell's height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// RestTime
if (indexPath.row % 2 == 1) {
return 40.0f;
}
// ExerciseTime
else {
return 65.0f;
}
}
-Number of Cells
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return (self.preset.blocks.count * 2) - 1;
}
-Cell for row
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row % 2 == 1) {
RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RestTimeTableViewCellIdentifier forIndexPath:indexPath];
RestTime *restTime = (RestTime *)[self.restTimeArray objectAtIndex:indexPath.row];
//CustomCell
return restTimeCell;
}else{
ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ExerciseTimeTableViewCellIdentifier forIndexPath:indexPath];
//Cell index
int index = (int)(indexPath.row / 2);
//exerciseTimes is a NSSet
ExerciseTime *exerciseTime = [self.preset.exerciseTimes.allObjects objectAtIndex:index];
//CustomCell
return exerciseTimecell;
}
return nil;
}
And the output is this :
I have tried to covert my NSSet to NSMutableArray and its still now working.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row % 2 == 1) {
RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:RestTimeTableViewCellIdentifier forIndexPath:indexPath];
RestTime *restTime = (RestTime *)[self.restTimeArray objectAtIndex:indexPath.row];
//CustomCell
return restTimeCell;
}else{
ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:ExerciseTimeTableViewCellIdentifier forIndexPath:indexPath];
NSMutableArray *array = [[self.preset.exerciseTimes allObjects] mutableCopy];
int index = (int)(indexPath.row / 2);
ExerciseTime *exerciseTime = [array objectAtIndex:index];
//CustomCell
return exerciseTimecell;
}
return nil;
}
As you can see that all the ExerciseCell is not in the right order. I cant figure out why it isn't in the right index after the cell is created. I want the order is sorted by the time its created not alphabet abcdef... or 123456... . Can anyone help me to find out what is the problem and how to tackle it.

I had found the problem and it was the NSSet is not sorted at the beginning and I sorted it with #"createdTime" and my problem was solved.
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"createdTime" ascending:YES];
NSArray *sortedArray = [self.exerciseTimes sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]];
Exercise *exerciseTime = (Exercise *)[sortedArray objectAtIndex:indexPath.row/2];

NSSet just be a set, there's no order between objects. If you'd like to keep the order, you can use NSArray (or NSMutableArray) instead of NSSet.

Please find my working Code and screenshot
#interface ViewController ()
#property (weak, nonatomic) IBOutlet UITableView *messageTableView;
#property (retain, nonatomic) NSMutableArray *datasourceArray;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.messageTableView registerNib:[UINib nibWithNibName:#"RestTimeTableViewCell" bundle:nil] forCellReuseIdentifier:#"RestTime"];
[self.messageTableView registerNib:[UINib nibWithNibName:#"ExerciseTimeTableViewCell" bundle:nil] forCellReuseIdentifier:#"ExerciseTime"];
self.messageTableView.separatorColor = [UIColor blackColor];
self.messageTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
self.datasourceArray = [[NSMutableArray alloc]init];
for (int i = 1; i <= 20; i++) {
[self.datasourceArray addObject:[NSString stringWithFormat:#"%d%d%d%d",i,i,i,i]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.datasourceArray.count * 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
// RestTime
if (indexPath.row % 2 == 1) {
return 40.0f;
}
// ExerciseTime
else {
return 65.0f;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row % 2 == 1) {
RestTimeTableViewCell *restTimeCell = (RestTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"RestTime" forIndexPath:indexPath];
//Access you object from array like this
return restTimeCell;
}
else {
ExerciseTimeTableViewCell *exerciseTimecell = (ExerciseTimeTableViewCell *)[tableView dequeueReusableCellWithIdentifier:#"ExerciseTime" forIndexPath:indexPath];
//Access you object from array like this
int index = (int)(indexPath.row / 2);
exerciseTimecell.exerciseName.text = [self.datasourceArray objectAtIndex:index];
return exerciseTimecell;
}
}
#end
Screenshot

Related

How to map Web-Services key and values pairs using NSObject?

Hi I have used NsurlSession for integrating web services when I get response from services I am using NSObject for mapping key and values pairs.
After the process is done in NSObject class I want to display that data in my TableList.
For this I wrote the code below, but after mapping all objects in my NSObject class.
How can I display them in tableList?
Please help me.
mainclass:-
#import "ViewController.h"
#interface ViewController (){
BacGroundGetMethodServiceClass * get;
ModelObject1 * model1;
NSString * alertmessage;
UITableView * MaintableView;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
get = [[BacGroundGetMethodServiceClass alloc]init];
get.delegate = self;
[get getServieCalling:#"my url"];
model1 = [[ModelObject1 alloc]init];
}
//got response here from services using protocols
- (void) GetCallService1: (id)MainResponse{
dispatch_async(dispatch_get_main_queue(), ^{
if ([MainResponse isKindOfClass:[NSDictionary class]] && MainResponse[#"error"]){
alertmessage = [MainResponse objectForKey:#"message"];
[self ShowingAlertMesaage:alertmessage];
}else if ([MainResponse count] == 0){
[self ShowingAlertMesaage:#"Server not responding please try again"];
}
else{
[model1 loadingservices :MainResponse];
}
});
}
//Crating TableList :-
-(void)createTableList{
//Create UITableList:-
[MaintableView removeFromSuperview];
MaintableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 118, self.view.frame.size.width-10, self.view.frame.size.height-75) style:UITableViewStylePlain];
MaintableView.delegate = self;
MaintableView.dataSource = self;
MaintableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
MaintableView.separatorStyle = UITableViewCellSeparatorStyleNone;
MaintableView.contentInset = UIEdgeInsetsMake(0, 0, 75, 0);
MaintableView.bounces = NO;
[self.view addSubview:MaintableView];
}
//TableList Delegate Methods:-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"HistoryCell";
// Similar to UITableViewCell, but
UITableViewCell *cell = (UITableViewCell *)[MaintableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
return cell;
}
#end
model Object class:-
#import "ModelObject1.h"
#implementation ModelObject1
#synthesize MasterId,Name;
-(void)loadingservices :(id)mainDictionary{
for (NSDictionary *obj in mainDictionary) {
if([obj objectForKey:#"Name"] && [obj objectForKey:#"id"]) {
Name = [obj objectForKey:#"Name"];
MasterId = [obj objectForKey:#"id"];
}
}
}
#end
If you want a list then you need array in proper JSON object.
i.e
(
{
Name = value1,
MasterId = value2
},
{
Name = value1,
MasterId = value2
},
{
Name = value1,
MasterId = value2
}
)
You need to create multiple objects of ModelObject1, i.e if in your JSON array you have 3 objects then you need to create 3 object of your ModelObject1.
You can achieve this by creating new Method or Class.
for example here is some code.
for(int i = 0; i < array.count; i++)
{
ModelObject1 *model1 = [[ModelObject1 alloc]init];
[model1 loadingservices :array[i];
//store model1 in to any array and use that array to display list in array.
}
You can display the data as below.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return yourModelClassArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"HistoryCell";
// Similar to UITableViewCell, but
UITableViewCell *cell = (UITableViewCell *)[MaintableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
ModelObject1 *model1 = yourModelClassArray[indexPath.row];
cell.textLabel.text = model1.Name;
return cell;
}

How to reload one table view row select then another tableview reload?

Below is my sample code. How to reload tblview(tableview)? Please help me.
#interface NewUIViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (nonatomic, strong) NSMutableArray *dataArray;
#property (weak, nonatomic) IBOutlet UITableView *tblview;
- (IBAction)btnAddRow:(id)sender;
#property (weak, nonatomic) IBOutlet UITableView *tblviewProject;
#property (nonatomic, strong) NSMutableArray *projectArray;
#end
#interface NewUIViewController ()
{ }
#end
#implementation NewUIViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.dataArray = [[NSMutableArray alloc] initWithObjects:#"Tiger",#"Leopard",#"Snow Leopard",#"Lion",nil];
self.projectArray = [[NSMutableArray alloc] initWithObjects:#"test1",#"test12",#"test1 Leopard",#"test13",nil];];
self.tblview.delegate= self;
self.tblview.dataSource=self;
self.tblviewProject.delegate= self;
self.tblviewProject.dataSource =self;
self.tblviewProject.frame = CGRectMake(50, 150, 600, 600);
}
-(BOOL)shouldAutorotate
{
return YES;
}
- (NSUInteger ) supportedInterfaceOrientations
{
return (UIInterfaceOrientationMaskLandscape);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tblview)
{
return [self.dataArray count];
}
else if (tableView == self.tblviewProject)
{
return [self.projectArray count];
}
return 0;
}
- (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];
cell.editingAccessoryType = YES;
if (tableView == self.tblview)
{
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
}
else if (tableView == self.tblviewProject)
{
cell.textLabel.text = [self.projectArray objectAtIndex:indexPath.row];
}
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tblviewProject)
{
NSMutableDictionary *newDic = [[NSMutableDictionary alloc] init];
NSDictionary *rowchange = (NSDictionary *) [self.dataArray objectAtIndex:[self.projIndexPath intValue]];
[newDic addEntriesFromDictionary:rowchange];
[newDic setObject:pname forKey:project];
[self.tblview beginUpdates];
[self.dataArray replaceObjectAtIndex:[self.projIndexPath intValue] withObject:newDic];
[self.tblview reloadData];
[self.tblview endUpdates];
}
}
#end
In you didSelectRowAtIndexPath func ,What 's pname and projIndexPath
And self.dataArray is NSString array but you replaceObjectAtIndex with a dictionary, it 's not correct
I don't know what do you want?
Update: you function runing but don't mean it 's correct
In Cellforrowatindexpath you set
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
But you replace a item in self.dataArray with a dictionary ==> you think, it 's working?
try:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tblviewProject)
{
[self.dataArray replaceObjectAtIndex:indexPath.row withObject:self.projectArray[indexPath.row]];
[self.tblview reloadData];
}
}
and replace pnam and projIndexPath as you want
AXXXXXXXXXXX
Update cellforrowat
- (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];
cell.editingAccessoryType = YES;
}
if (tableView == self.tblview)
{
cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
} else if (tableView == self.tblviewProject){
cell.textLabel.text = [self.projectArray objectAtIndex:indexPath.row];
}
return cell;
}
I's sure this working, when you reloaddata for tableview, cell is not nil, so, it 's not set data for cell

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.

Resources