iOS how to display dictionary keys into table cells - ios

I have a dictionary declared as "res". This "res" contains response of JSON data.
I did a valueforkey = "id" to retrieve out the list of id.
When I want to display each id into the tableview it turns out it only displays the same id repetively.
Here is my tableview:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [res count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableViews dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.textColor =[UIColor blackColor];
cell.textLabel.font = [UIFont systemFontOfSize:17.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
for(int i = 0; i<res.count; i++)
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[res valueForKey:#"id"]];
return cell;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] init];
return view;
}
When i NSLOG out the res with value "id" :
icon = [res valueForKey:#"id"];
NSLog(#"icon: %#", icon);
it shows:
icon: (
300122,
300228,
300235,
300272,
300265,
300242,
300198,
300135,
300282,
300255,
300245,
300248,
300185,
300118,
300275,
300295,
300005,
300062,
300068,
300055,
300095,
300008,
300018,
300015,
300058,
300012,
300085,
300038,
300105,
300002,
300072,
300022,
300025,
300028,
300035,
300258,
300088,
300262,
300128,
300215,
300142,
300078,
300205,
300315,
300238,
300302,
300232,
300285,
300132,
300102
)
Question is how do i display each id on each cell in the tableview?

Set an array of allKeys
NSArray *array = [NSArray arrayWithArray:[yourDictionary allKeys]];'
then just set your tableView dataSource using this array.
e.g
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableViews dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.textColor =[UIColor blackColor];
cell.textLabel.font = [UIFont systemFontOfSize:17.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[array objectAtIndex:indexPath.row]];
return cell;
}

Replace numberOfRowsInSection with:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *arrIds = (NSArray *)[res valueForKey:#"id"];
return arrIds.count;
}
And replace
for(int i = 0; i<res.count; i++)
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[res valueForKey:#"id"]];
with
NSArray *arrIds = (NSArray *)[res valueForKey:#"id"];
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[arrIds objectAtIndex:indexPath.row]];

Store your #"id" values in one array as follows;
NSArray *icon = [res valueForKey:#"id"];
NSLog(#"icon: %#", icon);
Then use that array to display values in TableView cell as follows;
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableViews dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[icon objectAtIndex:indexPath.row]];
return cell;
}

Replace line below
for(int i = 0; i<res.count; i++)
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[res valueForKey:#"id"]];
with line
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[[res valueForKey:#"id"] objectAtIndex:indexPath.row]];
your for loop logic is not correct to achieve the goal. We have tableView's default indexPath object to fetch current row in tableview, so fetch the value from your at the tableview's indexPath from your array.

in
ViewDidload{
NSArray * iconArray = [res allKeys];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableViews dequeueReusableCellWithIdentifier:#"cell"];
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
cell.textLabel.numberOfLines = 0;
cell.textLabel.textColor =[UIColor blackColor];
cell.textLabel.font = [UIFont systemFontOfSize:17.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [NSString stringWithFormat:#"ID: %#",[iconArray objectAtIndex:indexPath.row]];
return cell;
}

Related

Exactly two duplicated in tableview cell

I have the following code to populate data on the uitableview cell. For some reason, I see every item exactly two on the tableview.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"takeStockCell";
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
RackStockTakeStatus *rackStockTakeStatus = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = rackStockTakeStatus.locName;
if ([[rackStockTakeStatus.status lowercaseString] isEqualToString:#"inprogress"])
{
cell.detailTextLabel.textColor = [UIColor blueColor];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# [%#]",rackStockTakeStatus.status,rackStockTakeStatus.stockTakeByUser];
} else if ([[rackStockTakeStatus.status lowercaseString] isEqualToString:#"completed"])
{
cell.detailTextLabel.textColor = [UIColor colorWithRed:(0/255.0) green:(102/255.0) blue:(0/255.0) alpha:1];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# [%#]",rackStockTakeStatus.status,rackStockTakeStatus.stockTakeByUser];
} else if ([[rackStockTakeStatus.status lowercaseString] isEqualToString:#"verified"])
{
cell.detailTextLabel.textColor = [UIColor colorWithRed:(0/255.0) green:(102/255.0) blue:(0/255.0) alpha:1];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# [%#]",rackStockTakeStatus.status,rackStockTakeStatus.stockTakeByUser];
}
}
I am not sure about your method configuring the cell like that. Have you tried to configure it directly into the method cellForRowAtIndexPath ? Not putting the cell as a parameter.
Or just returning the cell in your method configure
cell = [self configureCell...

Cell for row at indexpath only called once

I am parsing a json data and in that one of the field is an array if it has a content.But if it has no content it is simply a string "No result."
I am using the following code to parse it :
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
//URL is called.
if ([status isEqualToString:#"success"])
{
if ([[[json objectForKey:#"Items"] objectForKey:#"item_list"] isKindOfClass:[NSString class]])
{
_Label.text = [NSString stringWithFormat:#"0"];
ItemsArray = [[NSMutableArray alloc]init];
}
else
{
ItemsArray = [[json objectForKey:#"Items"] objectForKey:#"item_list"];
NSLog(#"%d",[ItemsArray count]);
float Amount = 0;
NSLog(#"%d",[ItemsArray count]);
if ([ItemsArray count]>0)
{
for (int i=0; i<[ItemsArray count]; i++)
{
NSMutableDictionary * temp3 = [ItemsArray objectAtIndex: i];
NSString * x = [temp3 objectForKey:#"final"];
Amount = Amount + [x floatValue];
}
Label.text = [NSString stringWithFormat:#"%.2f",BidAmount];
}
else
{
Label.text = [NSString stringWithFormat:#"0"];
}
}
[TableViewOutlet reloadData];
}
This works fine.
When the field returns string i face no problem.But when the field is an array,I am stuck.
After running the project for the first time it works fine even if the array count is more than 0.But from second time onwards the Cellforrowatindexpath method is not called even when array count is more than 0....
These are my codes:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[ItemsArray count]);
return [ItemsArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TableViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell==nil)
{
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.025];
NSDictionary *temp = [ItemsArray objectAtIndex:indexPath.row];
UILabel *ItemName = (UILabel *)[cell viewWithTag:1000];
ItemName.text = [temp objectForKey:#"title"];
UILabel *Cost = (UILabel *)[cell viewWithTag:1001];
Cost.text = [temp objectForKey:#"final"];
return cell;
}
Someone please help me
I think the issue is that you have not retained your ItemArray.
NSArray* array = [[json objectForKey:#"Items"] objectForKey:#"item_list"];
ItemsArray = [NSMutableArray alloc]]initWithArray:array];
Use this code snippet..hope it will work.

CellForRowAtIndexPath not returning the same as didSelectRowAtIndexPath

I have a UiTableView containing Youtube Videos. The Youtube Videos are listed in the TableViewCells with the attributes title, author and link. The problem is when i try to return the value from the selected indexPath it returns another youtube video and not the one selected. why is it not returning the information from the selected video?
cellForRowAtIndexPath;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"cell"];
video = [items objectAtIndex:indexPath.row];
cell.textLabel.text = video.title;
cell.textLabel.numberOfLines = 2;
UIFont *myFont = [ UIFont fontWithName: #"Arial" size: 12.0 ];
cell.textLabel.font = myFont;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#\n%# views", video.author, FormatViewCount(video.viewcnt)];
cell.detailTextLabel.numberOfLines = 2;
UIFont *myFont1 = [ UIFont fontWithName: #"Arial" size: 10.0 ];
cell.detailTextLabel.font = myFont1;
[cell.imageView setImageWithURL:[NSURL URLWithString:video.thumb] placeholderImage:[UIImage imageNamed:#"blankvideo"]];
[cell.imageView.layer setBorderWidth:2];
[cell.imageView.layer setBorderColor:[UIColor whiteColor].CGColor];
return cell;
}
didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"%#", video.title);
NSLog(#"%#", video.author);
NSLog(#"%#", video.videoid);
NSLog(#"%d", thisObject.selectedRowNow);
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//---------add one more line---------//
video = [items objectAtIndex:indexPath.row];
//---------add one more line---------//
NSLog(#"%#", video.title);
NSLog(#"%#", video.author);
NSLog(#"%#", video.videoid);
NSLog(#"%d", thisObject.selectedRowNow);
}
You need to write:
video = [items objectAtIndex:indexPath.row];
before NSLog.
When you write video = [items objectAtIndex:indexPath.row]; you are just storing the last item that the tableview happens to have requested. No really point in storing it as an attribute of your class.
You can use a similar statement in your didSelectRowAtIndexPath:(NSIndexPath *)indexPath to retrieve the video that is actually selected:
Video *video = [items objectAtIndex:indexPath.row];

UITableView set checkbox state from database values

I am storing checkbox values (true/false) in database. I want to set checkbox checked/unchecked depending on the values stored in database. how to do that ? my code is,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%i",indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[checkedArr count]);
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
UIImage *image = (checked) ? [UIImage imageNamed:#"white_bg.png"] : [UIImage imageNamed:#"tick.png"];
cell.accessoryView = [[UIImageView alloc] initWithImage:image];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
BOOL checked = [[checkedArr objectAtIndex:indexPath.row] boolValue];
[checkedArr removeObjectAtIndex:indexPath.row];
[checkedArr insertObject:(checked) ? #"FALSE":#"TRUE" atIndex:indexPath.row];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
UIImage *newImage = (checked) ? [UIImage imageNamed:#"tick.png"] : [UIImage imageNamed:#"white_bg.png"];
cell.accessoryView=[[UIImageView alloc] initWithImage:newImage];
NSLog(#"Val is %i",val);
NSLog(#"selected is %#",[listArray objectAtIndex:indexPath.row]);
}
I am storing those values in database using an array checkedArr.
[dbObj insertQuestData:Question answers:listArray checkVal:checkedArr];
here dbObj is database object, others are values that i am storing to database.
Please let me know how to achieve the same.
The list array and checked array should be mutable array sent to database function which fills up the data.
self.listArray = [NSMutableArray array];
self.checkedArray = [NSMutableArray array];
[dbObj insertQuestData:Question answers:self.listArray checkVal:self.checkedArray];
// [self insertList:self.listArray andChecks:self.checkedArray];
The insertQuestData methods should fill up data like this -
- (void) insertList:(NSMutableArray *)list andChecks:(NSMutableArray *)checks
{
for (int i = 0; i < 100; i++) {
[list addObject:[NSString stringWithFormat:#"item %d", i]];
BOOL checkValue = (i % 4) == 0 ? YES : NO;
[checks addObject:[NSNumber numberWithBool:checkValue]];
}
}
The table datasource methods should be like this - (notice the commented line as correction to your code)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.listArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellIdentifier";//[NSString stringWithFormat:#"Cell%i",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
// cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
// cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[self.listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[self.checkedArray count]);
BOOL checked = [[self.checkedArray objectAtIndex:indexPath.row] boolValue];
UIImage *image = (!checked) ? [UIImage imageNamed:#"white_bg.png"] : [UIImage imageNamed:#"tick.png"];
cell.accessoryView = [[UIImageView alloc] initWithImage:image];
return cell;
}
This is what my sample code show on iPhone - [every 4th row is (green)ticked/selected and others are grey/unselected]
Feel free to ask if you have any specific questions / issues you face.

Xcode - Selected rows in table view does'nt retains its state

I am creating multiple lists like questions and answer session, question with multiple answers in table rows. But whenever I select a row other questions answers are also get selected and when I came back to same all the selections are gone. So how to avoid this ? Please help.
my code is,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(val==1)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<17; i++)
{
[checkedArr addObject:#"1"];
}
NSLog(#"Checked arr size %i",[checkedArr count]);
return 17;
}
else if(val==2)
{
checkedArr=[[NSMutableArray alloc] init];
for (int i = 0; i<13; i++)
{
[checkedArr addObject:#"1"];
}
return 13;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell%i",indexPath.row];
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell==nil)
{
cell= [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
}
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size:18.0];
UIView *selectionColor = [[UIView alloc] init];
selectionColor.backgroundColor = [UIColor colorWithRed:99/255.0f green:209/255.0f blue:248/255.0f alpha:1.0];
cell.selectedBackgroundView = selectionColor;
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView.hidden=TRUE;
//cell.accessoryView=Nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
cell.textLabel.frame=CGRectMake(75.0, 50.0, 150.0, 20.0);
cell.textLabel.text=[listArray objectAtIndex:indexPath.row];
NSLog(#"Checked arr size %i",[checkedArr count]);
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell=[questionTable cellForRowAtIndexPath:indexPath];
[checkedArr replaceObjectAtIndex:indexPath.row withObject:#"0"];
if([[checkedArr objectAtIndex:indexPath.row] isEqual:#"0"])
{
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"tick.png"]];
[checkedArr addObject:indexPath];
NSLog(#"checkedArr 0000000");
}
else if ([[checkedArr objectAtIndex:indexPath.row] isEqual:#"1"])
{
cell.accessoryView=nil;
[checkedArr removeObject:indexPath];
NSLog(#"checkedArr 111111");
}
[questionTable deselectRowAtIndexPath:indexPath animated:YES];
//[self.questionTable reloadData];
NSLog(#"Val is %i",val);
NSLog(#"selected is %#",[listArray objectAtIndex:indexPath.row]);
// NSLog(#"Checked arr descripton %#",[checkedArr description]);
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.accessoryView = nil;
}

Resources