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
Related
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
I have created a page where i need to use two table views for adding dynamic options. The problem is that only one table is displaying its data and the other one is not. Am totally confused where did i do wrong.
screen shot of my views.
Below am adding my code-
#interface FlirtMatchViewController ()
{
UILabel *headerTitle;
NSArray *tableData;
NSArray *arrimages;
NSArray *tableData1;
NSArray *arrimages1;
}
#end
#implementation FlirtMatchViewController
- (void)viewDidLoad {
[super viewDidLoad];
tableData = [NSArray arrayWithObjects:#"TattooSingles",#"Eyecatcher",#"Tattoo Toplist",#"Radar",#"Flirt Chat",#"Free VIP Membership",#"VIP Membership",#"Invite Friends",nil];
arrimages = [NSArray arrayWithObjects:#"tatto_single#2x.png",#"eye_catcher.png",#"tatto_toplist.png",#"radar.png",#"Flirt_chat.png",#"free_vip.png",#"vip_membership_navigation.png",#"add-friend1.png", nil];
tableData1 = [NSArray arrayWithObjects:#"TattooSingles",#"Eyecatcher",#"Tattoo Toplist",#"Radar",#"Flirt Chat",#"Free VIP Membership",#"VIP Membership",#"Invite Friends",nil];
arrimages1 = [NSArray arrayWithObjects:#"tatto_single#2x.png",#"eye_catcher.png",#"tatto_toplist.png",#"radar.png",#"Flirt_chat.png",#"free_vip.png",#"vip_membership_navigation.png",#"add-friend1.png", nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView==_leftTableView)
{
return [tableData count];
}
else {
return [tableData1 count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier2 = #"Cell2";
static NSString *CellIdentifier1 = #"Cell1";
if(tableView==self.leftTableView)
{
static NSString *CellIdentifier1 = #"Cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] ;
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
else
{
static NSString *CellIdentifier2 = #"Cell2";
UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell1 == nil)
{
cell1= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] ;
}
cell1.textLabel.text = [tableData1 objectAtIndex:indexPath.row];
return cell1;
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
TattooSinglesScreen *obj=[self.storyboard instantiateViewControllerWithIdentifier:#"TattooSinglesScreen"];
EyecatcherScreen *obj1=[self.storyboard instantiateViewControllerWithIdentifier:#"EyecatcherScreen"];
TattooToplist *obj2=[self.storyboard instantiateViewControllerWithIdentifier:#"TattooToplist"];
int i=indexPath.row;
if(i==0){
[self.navigationController pushViewController:obj animated:NO];
}
else if (i==1) {
[self.navigationController pushViewController:obj1 animated:NO];
}
else if (i==2) {
[self.navigationController pushViewController:obj2 animated:NO];
}
}
Also am trying to navigate the first three options to their particular screen by using the code below. But the code is not working for me. Can anyone clear my doubts?
What Anbu suggested will work, although could I suggest you create separate classses to handle the datasource and delegate for each UITableView, then simply assign the datasource and delegate to your new classes for each tableview. This will be cleaner and might help resolve the logic issues you have.
Hope this helps, comment if you have any questions, good luck.
do like
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self. leftTableView)
{
return [tableData count];
}
if (tableView == self. rightTableView)
{
return [tableData1 count];
}
}
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
if(tableView==self.leftTableView)
{
static NSString *CellIdentifier1 = #"Cell1";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1] ;
}
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
return cell;
}
if (tableView == self._rightTableView)
{
static NSString *CellIdentifier2 = #"Cell2";
UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if (cell1 == nil)
{
cell1= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2] ;
}
cell1.textLabel.text = [tableData1 objectAtIndex:indexPath.row];
return cell1;
}
}
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.
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'm new to the whole iOS developement, so not really good at it. I currently have a viewController with two tableviews. The first table is always visible and contains categories. The second table should only be visible when a cell from the first table is selected. The second table then contains subitems from the cell that was selected in the first tableview. Both tableviews are connected to their property in the .h file.
The viewcontroller itself is connected to a FoodAddViewController.h and FoodAddViewController.m file.
In the FoodAddViewController.h file, I have:
#import <UIKit/UIKit.h>
#class FoodAddViewController;
#interface FoodAddViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *Categorien;
#property (strong, nonatomic) IBOutlet UITableView *Invulling;
- (IBAction)cancel:(id)sender;
#end
For the FoodAddViewController.m, I have:
#interface FoodAddViewController ()
{
NSArray *CategoryLabel;
NSMutableArray *elementen;
}
#end
#implementation FoodAddViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.Categorien.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Categorien.frame=CGRectMake(0,200, 700,234);
[self.Invulling setHidden:TRUE];
self.Invulling.layer.transform = CATransform3DRotate(CATransform3DIdentity,-1.57079633,0,0,1);
self.Invulling.frame=CGRectMake(0,200, 700,234);
self.Categorien.dataSource = self;
self.Categorien.delegate = self;
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"categorie" ofType:#"txt"];
NSString *content = [NSString stringWithContentsOfFile:filePath
encoding:NSMacOSRomanStringEncoding
error:NULL];
NSArray * categories = [content componentsSeparatedByString:#"\n"];
CategoryLabel = categories;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(self.Categorien==tableView) {
return CategoryLabel.count;
}
if(self.Invulling==tableView) {
return elementen.count;
}
return 0;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(self.Categorien==tableView) {
static NSString *CellIdentifier = #"Cell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [CategoryLabel objectAtIndex:indexPath.row];
return Cell;
}
if(self.Invulling==tableView) {
static NSString *CellIdentifier = #"DetailCell";
CustomCell *Cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!Cell) {
Cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
Cell.layer.transform = CATransform3DRotate(CATransform3DIdentity,1.57079633,0,0,1);
Cell.frame=CGRectMake(0,0,234,150);
Cell.textLabel.text = [elementen objectAtIndex:indexPath.row];
return Cell;
}
return NULL;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 200;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.Invulling.dataSource = self;
self.Invulling.delegate = self;
elementen = [[NSMutableArray alloc]init];
if(self.Categorien==tableView) {
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
PFQuery *query = [PFQuery queryWithClassName:cellText];
[query selectKeys:#[#"Naam"]];
NSArray *result = [query findObjects];
for (PFObject *object in result) {
NSString *naam = object[#"Naam"];
if(![elementen containsObject:naam]) {
[elementen addObject:naam];
}
}
}
[self.Invulling setHidden:FALSE];
[self.Invulling reloadData];
}
end
Now, the problem is that the reloadData method does not work correctly. For example: if I press the first cell from the first tableview (Categorien), then nothing happens. But when I click another cell, the second tableview (Invulling) gets loaded with the results from the first cell.
you have to use didSelectRowAtIndexPath not didDeselectRowAtIndexPath method
Also look up some tutorial on debugging, you could have known that the method is not
being called if you have added breakpoints
You are using
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:
Instead, use
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: