how do we access values stored in NSMutableArray of NSMutableDictionary? - iphone

I have stored values in NsMutableDictionaries . ThenI stored all the dictionaries in NSMutable Array. I need to access the values ? How can I do that ?
-(void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Library";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStyleBordered target:self action:#selector(close:)];
cells = [[NSMutableArray alloc] initWithObjects:#"dict1", #"dict2", #"dict3", #"dict4", #"dict5", #"dict6", nil];
dict1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 01 Feb #2", #"date", #"0.7", #"time", #"1.2MB", #"size", #"200*200", #"pix", nil];
dict2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Wed, 02 Mar #3", #"date", #"1.2", #"time", #"2.2MB", #"size", #"300*300", #"pix", nil];
dict3 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Tue, 03 Apr #5", #"date", #"1.7", #"time", #"2.5MB", #"size", #"240*240", #"pix", nil];
dict4 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 01 Feb #2", #"date", #"0.7", #"time", #"1.2MB", #"size", #"200*200", #"pix", nil];
dict5 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 10 Nov #5", #"date", #"2.7", #"time", #"4.2MB", #"size", #"200*400", #"pix", nil];
dict6 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"Mon, 11 Dec #6", #"date", #"4.7", #"time", #"2.2MB", #"size", #"500*200", #"pix", nil];
//[cells addObject:dict1];
//[cells addObject:dict2];
//[cells addObject:dict3];
//[cells addObject:dict4];
//[cells addObject:dict5];
//[cells addObject:dict6];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cells 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
//cell.contentView.frame = CGRectMake(0.0f, 0.0f, 320.0f, 80.0f);
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
UIImageView *image1 = [[UIImageView alloc]init];
image1.frame = CGRectMake(0.0f, 0.0f, 80.0f, 80.0f);
image1.tag = tag7;
UILabel *dateLabel = [[UILabel alloc]init];
dateLabel.frame = CGRectMake(100.0f, 5.0f, 120.0f, 25.0f);
dateLabel.font = [UIFont fontWithName:#"Georgia" size:10];
dateLabel.tag = tag1;
UILabel *timeLabel = [[UILabel alloc] init];
timeLabel.frame = CGRectMake(100.0f, 30.0f, 40.0f, 25.0f);
timeLabel.font = [UIFont fontWithName:#"Georgia" size:10];
timeLabel.tag = tag2;
UILabel *sizeLabel = [[UILabel alloc] init];
sizeLabel.frame = CGRectMake(160.0f, 30.0f, 40.0f, 25.0f);
sizeLabel.font = [UIFont fontWithName:#"Georgia" size:10];
sizeLabel.tag = tag3;
UILabel *pixLabel = [[UILabel alloc] init];
pixLabel.frame = CGRectMake(220.0f, 30.0f, 40.0f, 25.0f);
pixLabel.font = [UIFont fontWithName:#"Georgia" size:10];
pixLabel.tag = tag4;
UILabel *shareLabel = [[UILabel alloc] init];
shareLabel.frame = CGRectMake(100.0f, 55.0f, 100.0f, 25.0f);
shareLabel.font = [UIFont fontWithName:#"Georgia" size:10];
shareLabel.tag = tag5;
UILabel *deleteLabel = [[UILabel alloc] init];
deleteLabel.frame = CGRectMake(220.0f, 55.0f, 100.0f, 25.0f);
deleteLabel.font = [UIFont fontWithName:#"Georgia" size:10];
deleteLabel.tag = tag6;
[cell.contentView addSubview:dateLabel];
[cell.contentView addSubview:timeLabel];
[cell.contentView addSubview:sizeLabel];
[cell.contentView addSubview:pixLabel];
[cell.contentView addSubview:shareLabel];
[cell.contentView addSubview:deleteLabel];
[cell.contentView addSubview:image1];
[dateLabel release];
[timeLabel release];
[sizeLabel release];
[pixLabel release];
[shareLabel release];
[deleteLabel release];
[image1 release];
}
// Set up the cell...
[(UILabel *)[cell viewWithTag:tag1] setText:[cells objectAtIndex:[dict1 objectForKey: #"date"]]];
[(UILabel *)[cell viewWithTag:tag2] setText:[cells objectAtIndex:[dict1 objectForKey: #"time"]]];
[(UILabel *)[cell viewWithTag:tag3] setText:[cells objectAtIndex:[dict1 objectForKey: #"size"]]];
[(UILabel *)[cell viewWithTag:tag4] setText:[cells objectAtIndex:[dict1 objectForKey: #"pix"]]];
[(UILabel *)[cell viewWithTag:tag5] setText:#"Share"];
[(UILabel *)[cell viewWithTag:tag6] setText:#"Delete"];
cell.imageView.image = [UIImage imageNamed:#"image2.png"];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80.0f;
}
I did in above way but it is not working. I know the mistake is at the accessing values. but, I could not get how to do it ?
Thank You.

You haven't stored the dictionaries at all—just the strings "dict1", "dict2", "dict3", and so on. The array initializer you're using should be something like
cells = [[NSMutableArray alloc] initWithCapacity:6];
I'm not sure why you've got all of the [cells addObject:dictionaryN]; lines commented out, because that's the correct way to add the dictionaries to the array; you also need to have a [dictionaryN release]; after each of them to prevent memory leaks.
To get the values out of the dictionaries in the array, you need to do something like this in your -tableView:cellForRowAtIndexPath: method:
NSDictionary *rowDictionary = [cells objectAtIndex:indexPath.row];
[(UILabel *)[cell viewWithTag:tag1] setText:[rowDictionary objectForKey:#"date"]];
[(UILabel *)[cell viewWithTag:tag2] setText:[rowDictionary objectForKey:#"time"]];
// etc.

Related

How to set Title for cell using Dictionary

I want to use NSDictionary instead of cell Array.
Following is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
//Add the Bg Image to the cell
//Add the Label
UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 300, 30)];
[cellTitle setBackgroundColor:[UIColor clearColor]];
[cellTitle setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[cellTitle setTextColor:[UIColor darkGrayColor]];
[cellTitle setText:[[cellArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
[cell.contentView addSubview:cellTitle];
return cell;
}
NSDictionary *dictionary1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"ABC",#"Name",#"12",#"Age", nil];
NSDictionary *dictionary2 = [[NSDictionary alloc] initWithObjectsAndKeys:#"DEF",#"Name",#"14",#"Age", nil];
NSDictionary *dictionary3 = [[NSDictionary alloc] initWithObjectsAndKeys:#"GHI",#"Name",#"16",#"Age", nil];
NSDictionary *dictionary4 = [[NSDictionary alloc] initWithObjectsAndKeys:#"JKL",#"Name",#"18",#"Age", nil];
NSArray *array = [[NSArray alloc] initWithObjects:dictionary1,dictionary2,dictionary3,dictionary4, nil];
Now in the cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
//Add the Bg Image to the cell
//Add the Label
UILabel *cellTitle=[[UILabel alloc]initWithFrame:CGRectMake(15, 7, 300, 30)];
[cellTitle setBackgroundColor:[UIColor clearColor]];
[cellTitle setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[cellTitle setTextColor:[UIColor darkGrayColor]];
[cellTitle setText:[[array objectAtIndexPath:indexPath.row] objectForKey:#"Name"]];
[cell.contentView addSubview:cellTitle];
return cell;
}
also in the numberOfRowsInSection:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
You can use newer syntax like this
NSDictionary *dict = #{#"key" : #"value", #"key2" : #"value2"};
NSDictionary *dict2 = #{#"key" : #"value", #"key2" : #"value2"};
NSArray *array = #(dict, dict2);

TableView cell Labels are disappearing on scrolling, but visible for a selected cell?

As TableView cell labels are displayed on load but when the tableView is scrolled the tableview contents are not appearing. But if I select any of the cell then the labels in that particular cell are displaying.
Please help me. I have the same problem in different aspect too. I did not get any resolution for it.
Here is my code of cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
UILabel *usr = (UILabel *)[cell viewWithTag:101];
usr.font = [UIFont boldSystemFontOfSize:12.0];
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
status = (UILabel *)[cell viewWithTag:102];
status.font = [UIFont boldSystemFontOfSize:12.0];
[status setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
[rival release];
UILabel *rivals = (UILabel *)[cell viewWithTag:103];
rivals.font = [UIFont boldSystemFontOfSize:12.0];
[rivals setText:[appDelegate.rivalusernames objectAtIndex:[indexPath row]]];
UILabel *gamename = [[UILabel alloc] initWithFrame:CGRectMake(84,27,208,21)];
gamename.tag = 104;
[cell.contentView addSubview:gamename];
[gamename release];
UILabel *gamenames = (UILabel *)[cell viewWithTag:104];
gamenames.font = [UIFont boldSystemFontOfSize:12.0];
[gamenames setText:[appDelegate.challengenames objectAtIndex:[indexPath row]]];
UILabel *time = [[UILabel alloc] initWithFrame: CGRectMake(84,47,149,21)];
time.tag = 105;
[cell.contentView addSubview:time];
[time release];
UILabel *times = (UILabel *)[cell viewWithTag:105];
times.font = [UIFont boldSystemFontOfSize:12.0];
[times setText:[appDelegate.remainingtime objectAtIndex:[indexPath row]]];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
NSURL *url = [NSURL URLWithString:[appDelegate.imagepaths objectAtIndex:[indexPath row]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:106];
imgView.image = img;
return cell;
}
first of all move these lines inside the if (cell==NIL):
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
}
or you add a subview to the cell each time you reuse it, scrolling
and the same for:
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
and
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
...etc etc
as a general rule: you add/alloc new objects just once when you first create a cell (inside the if (cell==nil))
then outside that if you just reuse all objects and change their properties, as text of image source...
Maybe the color of your UILabels is the same as the background color? When you select a cell and then you can see the text, it probably is because of the then highlighted cell color ...
And I also strongly suggest you make a cell subclass as cortez mentioned, this code is not read- nor maintainable ...
your implementation of the UITableView Cell is rong try this way
i Know your problem will solve.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
{
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
usr.font = [UIFont boldSystemFontOfSize:12.0];
[cell.contentView addSubview:user];
[user release];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
status.font = [UIFont boldSystemFontOfSize:12.0];
[cell.contentView addSubview:status];
[status release];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
[rival release];
}
else
{
UILabel *usr = (UILabel *)[cell viewWithTag:101];
status = (UILabel *)[cell viewWithTag:102];
rival = (UILabel *)[cell viewWithTag:103];
}
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
[status setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
[rival setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
return cell;
}
Initially I written the code as above. After the suggestion of meronix I have changed to below one. Please suggest.
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if (tableView.tag ==16)
{
NSLog(#"%d",appDelegate.checkChallenges);
static NSString *CellIdentifier = #"newsTableCell";
UITableViewCell *cell = [self.newsTable dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil) {
cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
UILabel *user = [[UILabel alloc] initWithFrame:CGRectMake(84, 10,75,21)];
user.tag = 101;
[cell.contentView addSubview:user];
[user release];
UILabel *status = [[UILabel alloc] initWithFrame:CGRectMake(154,10,69,21)];
status.tag = 102;
[cell.contentView addSubview:status];
[status release];
UILabel *rival = [[UILabel alloc] initWithFrame:CGRectMake(220,10,80,21)];
rival.tag = 103;
[cell.contentView addSubview:rival];
//[rival release];
UILabel *gamename = [[UILabel alloc] initWithFrame:CGRectMake(84,27,208,21)];
gamename.tag = 104;
[cell.contentView addSubview:gamename];
[gamename release];
UILabel *time = [[UILabel alloc] initWithFrame: CGRectMake(84,47,149,21)];
time.tag = 105;
[cell.contentView addSubview:time];
[time release];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(12,10,67,58)];
imageView.tag = 106;
[cell.contentView addSubview:imageView];
[imageView release];
}
UILabel *usr = (UILabel *)[cell viewWithTag:101];
usr.font = [UIFont boldSystemFontOfSize:12.0];
[usr setText:[appDelegate.usernames objectAtIndex:[indexPath row]]];
UILabel *stat = (UILabel *)[cell viewWithTag:102];
stat.font = [UIFont boldSystemFontOfSize:12.0];
[stat setText:[appDelegate.statistics objectAtIndex:[indexPath row]]];
NSURL *url = [NSURL URLWithString:[appDelegate.imagepaths objectAtIndex:[indexPath row]]];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
UIImageView *imgView = (UIImageView *)[cell viewWithTag:106];
imgView.image = img;
UILabel *times = (UILabel *)[cell viewWithTag:105];
times.font = [UIFont boldSystemFontOfSize:12.0];
[times setText:[appDelegate.remainingtime objectAtIndex:[indexPath row]]];
UILabel *gamenames = (UILabel *)[cell viewWithTag:104];
gamenames.font = [UIFont boldSystemFontOfSize:12.0];
[gamenames setText:[appDelegate.challengenames objectAtIndex:[indexPath row]]];
UILabel *rivals = (UILabel *)[cell viewWithTag:103];
rivals.font = [UIFont boldSystemFontOfSize:12.0];
[rivals setText:[appDelegate.rivalusernames objectAtIndex:[indexPath row]]];
return cell;
}

UITableView custom cells always change there content - must stop it

i have a UITableView with custom cells (code below) that load the data from NSDictionary (the NSDictionary loads there data from NSArray objectatIndexPath:indexpath.row.
Now, i have a DidSelectRow functions that works in the same way (NSArray -> NSDictionary -> Cell data).
the problem is that when im scrolling my table its change my cells contant.
i must have my cells always reload that same order. and i must stop this reloading data when scrolling.
This is the code im using to load my table view and load data to table view cells and my didSelectRow: Please help, i dont have time for this problem...
RequestArray = [jsonDictionary objectForKey:#"Content"];
RequestTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 84, 320, 326)];
RequestTable.backgroundColor = [UIColor colorWithRed:(234/255.f) green:(234/255.f) blue:(234/255.f) alpha:1];
RequestTable.dataSource=self;
RequestTable.delegate=self;
RequestTable.rowHeight = 77;
[self.view addSubview:RequestTable];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
NSDictionary *object = [RequestArray objectAtIndex:indexPath.row];
NSString *Category = [object valueForKey:#"Category"];
NSString *ItemDescription = [object valueForKey:#"ItemDescription"];
NSString *ItemName = [object valueForKey:#"ItemName"];
NSString *Date = [object valueForKey:#"Date"];
NSString *ExpiresDate = [object valueForKey:#"ExpiresDate"];
BOOL isRead = [[object valueForKey:#"IsRead"]boolValue];
/// add time label to cell
NSTimeInterval TIMEinterval = [Date intValue];
NSDate* TIMEDate = [NSDate dateWithTimeIntervalSince1970:TIMEinterval];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"HH:mm"];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2]]; //+0000
NSString* dateStrig = [df stringFromDate:TIMEDate];
UILabel *RequestTime = [[UILabel alloc]initWithFrame:CGRectMake(268, 8, 33, 16)];
[RequestTime setTextAlignment:UITextAlignmentRight];
RequestTime.backgroundColor = [UIColor clearColor];
RequestTime.textColor = [UIColor blackColor];
[RequestTime setFont:[UIFont systemFontOfSize:12]];
RequestTime.text = dateStrig;
[cell addSubview:RequestTime];
/// add experation label to cell
NSTimeInterval EXPTIMEinterval = [ExpiresDate intValue];
NSDate* EXPDate = [NSDate dateWithTimeIntervalSince1970:EXPTIMEinterval];
NSTimeInterval secondsBetween = [EXPDate timeIntervalSinceDate:TIMEDate];
int numberOfHours = secondsBetween / 3600;
UILabel *ExperationTime = [[UILabel alloc]initWithFrame:CGRectMake(152, 24, 150, 15)];
ExperationTime.backgroundColor = [UIColor clearColor];
[ExperationTime setTextAlignment:UITextAlignmentRight];
ExperationTime.textColor = [UIColor colorWithRed:(255/255.f) green:(103/255.f) blue:(18/255.f) alpha:1];
[ExperationTime setFont:[UIFont systemFontOfSize:14]];
if (numberOfHours>24){
numberOfHours = numberOfHours/24;
ExperationTime.text = [NSString stringWithFormat:#"המוצר דרוש תוך %d ימים",numberOfHours];
}else{
ExperationTime.text = [NSString stringWithFormat:#"המוצר דרוש תוך %d שעות",numberOfHours];
}
[cell addSubview:ExperationTime];
// add item category to cell
UILabel *itamCategory = [[UILabel alloc]initWithFrame:CGRectMake(143 , 5, 120, 21)];
itamCategory.backgroundColor = [UIColor clearColor];
[itamCategory setTextAlignment:UITextAlignmentRight];
itamCategory.textColor = [UIColor colorWithRed:(0/255.f) green:(177/255.f) blue:(233/255.f) alpha:1];
[itamCategory setFont:[UIFont boldSystemFontOfSize:17]];
itamCategory.text = Category;
[cell addSubview:itamCategory];
// add item Name to cell
UILabel *itamName = [[UILabel alloc]initWithFrame:CGRectMake(98, 39, 203, 21)];
itamName.backgroundColor = [UIColor clearColor];
[itamName setTextAlignment:UITextAlignmentRight];
itamName.textColor = [UIColor blackColor];
[itamName setFont:[UIFont boldSystemFontOfSize:17]];
itamName.text = ItemName;
[cell addSubview:itamName];
// add item Description to cell
UILabel *Description = [[UILabel alloc]initWithFrame:CGRectMake(98, 62, 203, 10)];
Description.backgroundColor = [UIColor clearColor];
[Description setTextAlignment:UITextAlignmentRight];
Description.textColor = [UIColor blackColor];
[Description setFont:[UIFont systemFontOfSize:13]];
Description.text =ItemDescription;
[cell addSubview:Description];
//add sendOffer button
UIButton *callSeller = [UIButton buttonWithType:UIButtonTypeCustom];
callSeller.frame = CGRectMake(25, 8, 54, 45);
[callSeller setTag:indexPath.row];
[callSeller setBackgroundImage:[UIImage imageNamed:#"makeOfferTable.png"] forState:UIControlStateNormal];
[callSeller setBackgroundImage:[UIImage imageNamed:#"makeOfferTable.png"] forState:UIControlStateHighlighted];
[callSeller addTarget:self action:#selector(makeaOffer:) forControlEvents:UIControlEventAllEvents];
[cell addSubview:callSeller];
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"highlightCellBG.png"]];
cell.selectedBackgroundView = myBackView;
cell.backgroundColor = [UIColor lightGrayColor];
//add newOffer sign (if new)
if (!isRead){
UIImageView *newIndocator = [[UIImageView alloc]initWithFrame:CGRectMake(295, 0, 25, 25)];
newIndocator.image = [UIImage imageNamed:#"newOfferIndicator.png"];
[newIndocator setContentMode:UIViewContentModeScaleToFill];
[cell addSubview:newIndocator];
}
}
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSDictionary *object = [RequestArray objectAtIndex:indexPath.row];
NSLog(#"indePath.row = %d",indexPath.row);
Seller_RequestDetailsViewController *infoView = [[Seller_RequestDetailsViewController alloc]initWithNibName:#"Seller_RequestDetailsViewController" bundle:nil];
NSString *OfferDate = [object valueForKey:#"Date"];
NSTimeInterval TIMEinterval = [OfferDate intValue];
NSDate* TIMEDate = [NSDate dateWithTimeIntervalSince1970:TIMEinterval];
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"DD/MM/yyyy"];
[df setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:2]]; //+0000
infoView.date = [df stringFromDate:TIMEDate];
infoView.itemName = [object valueForKey:#"ItemName"];
infoView.modalName = [object valueForKey:#"ItemDegem"];
infoView.buyerID = [NSString stringWithFormat:#"%#",[object valueForKey:#"BuyerUserID"]];
infoView.city = [object valueForKey:#"Region"];
infoView.Offerdescription = [object valueForKey:#"ItemDescription"];
BOOL isRead = [[object valueForKey:#"IsRead"]boolValue];
infoView.modalTransitionStyle = UIModalTransitionStylePartialCurl;
[self presentModalViewController:infoView animated:YES];
if (!isRead){
[self markOfferAsRead:[NSString stringWithFormat:#"%#",[object valueForKey:#"ItemID"]]];
}
}
I am not sure I understand your problem completely but I do see an error in the way you build the cells. After dequeueing the cell, you should only init the cell if it's nil NOT init and build the cell.
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
if(cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier];
}
// Now build the cell.
If you don't rebuild the cell every time, it will just reuse the cell that was originally built.
your problem is that everything is with in this:
if(cell == nil) {
//Your Code
}
What is happening is the tableview reuses cells. You are only changing the content if(cell == nil).
What you need is to only create a new cell in side if(cell == nil)
and move the rest of your code out of that if statement

How can I search data from tableview cell?

I have an UITableview controller which representing fetched XML data. For representing these data I used five UILabel. Now I have to add a searchbar at the top of the UITableview. So programmatically I have added a searchbar.
Now I have used searching theorem for search data from the UITableview. But It is not working. I can search data from UItableview when only one text in the UItableviewcell without any UIlabel or something else but in my UItableviewcell cell are taking five UILabel that's why it's becoming tough for me to search data from the UItableviewcell. For understanding I am attaching my code how I am representing my XML data in tableview cell.
This is my XML data representation in UITableviewCell...
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:15.0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
cell.accessoryView = imageView;
cell.accessoryType = UITableViewCellSelectionStyleNone;
tableView.separatorColor = [UIColor clearColor];
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
cellView = [[[UIView alloc] initWithFrame:CGRectMake(5,8,290, 120)] autorelease];
cellView.backgroundColor = [UIColor clearColor];
cellView.tag =10;
[cell.contentView addSubview:cellView];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(2, 40, 48, 48)];
imgView.image = [UIImage imageNamed:#"productbox.png"];
imgView.layer.borderColor = [UIColor blackColor].CGColor;
imgView.layer.borderWidth = 2.0;
imgView.tag = 5;
[cellView addSubview:imgView];
CGRect idLabelRect = CGRectMake(65, 0, 190, 18);
idLabel = [[[UILabel alloc] initWithFrame:idLabelRect] autorelease];
idLabel.textAlignment = UITextAlignmentLeft;
idLabel.textColor = [UIColor blackColor];
idLabel.font = [UIFont systemFontOfSize:12];
idLabel.backgroundColor = [UIColor clearColor];
idLabel.layer.borderColor = [UIColor grayColor].CGColor;
idLabel.tag = 0;
CGRect statusRect = CGRectMake(65, 22, 190, 22);
statusLabel = [[[UILabel alloc] initWithFrame:statusRect] autorelease];
statusLabel.textAlignment = UITextAlignmentLeft;
statusLabel.textColor = [UIColor blackColor];
statusLabel.font = [UIFont systemFontOfSize:12];
statusLabel.backgroundColor = [UIColor clearColor];
statusLabel.layer.borderColor = [UIColor grayColor].CGColor;
statusLabel.tag = 1;
CGRect orderDateRect = CGRectMake(65, 48, 190, 22);
orderDate = [[[UILabel alloc] initWithFrame:orderDateRect] autorelease];
orderDate.textAlignment = UITextAlignmentLeft;
orderDate.textColor = [UIColor blackColor];
orderDate.font = [UIFont systemFontOfSize:12];
orderDate.backgroundColor = [UIColor clearColor];
orderDate.layer.borderColor = [UIColor grayColor].CGColor;
orderDate.tag = 2;
CGRect byRect = CGRectMake(65, 75, 190, 22);
byLabel = [[[UILabel alloc] initWithFrame:byRect] autorelease];
byLabel.textAlignment = UITextAlignmentLeft;
byLabel.textColor = [UIColor blackColor];
byLabel.font = [UIFont systemFontOfSize:12];
byLabel.backgroundColor = [UIColor clearColor];
byLabel.layer.borderColor = [UIColor grayColor].CGColor;
byLabel.tag = 3;
CGRect totalRect = CGRectMake(65, 98, 190, 22);
totalLabel = [[[UILabel alloc] initWithFrame:totalRect] autorelease];
totalLabel.textAlignment = UITextAlignmentLeft;
totalLabel.textColor = [UIColor blackColor];
totalLabel.font = [UIFont systemFontOfSize:12];
totalLabel.backgroundColor = [UIColor clearColor];
totalLabel.layer.borderColor = [UIColor grayColor].CGColor;
totalLabel.tag = 4;
[cellView addSubview:idLabel];
[cellView addSubview:statusLabel];
[cellView addSubview:orderDate];
[cellView addSubview:byLabel];
[cellView addSubview:totalLabel];
}
if(searching == YES){
//[cell setText:[tableData objectAtIndex:indexPath.row]];
cell.textLabel.text = [tableData objectAtIndex:indexPath.row];
}
else{
cellView = (UIView *)[cell.contentView viewWithTag:10];
idLabel = (UILabel *)[cellView viewWithTag:0];
statusLabel = (UILabel *)[cellView viewWithTag:1];
orderDate = (UILabel *)[cellView viewWithTag:2];
byLabel = (UILabel *)[cellView viewWithTag:3];
totalLabel = (UILabel *)[cellView viewWithTag:4];
imgView = (UIImageView *)[cellView viewWithTag:5];
if(pendingOrder == NO && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[records objectAtIndex:indexPath.section] objectAtIndex:4]];
}
else if(pendingOrder == YES && todaysOrder == NO){
idLabel.text = [NSString stringWithFormat:#"Order Id: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:0]];
statusLabel.text = [NSString stringWithFormat:#"Status: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:1]];
orderDate.text = [NSString stringWithFormat:#"Date: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:2]];
byLabel.text =[NSString stringWithFormat:#"By: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:3]];
totalLabel.text =[NSString stringWithFormat:#"Total: %#",[[pendingRecords objectAtIndex:indexPath.section] objectAtIndex:4]];
}
}
return cell;
}
And this searching Delegate.....
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
searching = YES;
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
searching = NO;
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] && searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
searching = NO;
[tableData addObjectsFromArray:dataSource];
#try{
searching = NO;
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[sBar resignFirstResponder];
}
For more help to understand i am also attaching my viewDidLoad....
//Add the search bar
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,0,320,50)];
sBar.delegate = self;
searching = NO;
[self.view addSubview:sBar];
tableview.dataSource = self;
tableview.delegate = self;
//initialize the two arrays; datasource will be initialized and populated by appDelegate
searchData = [[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc] init];
[tableData addObjectsFromArray:dataSource];//on launch it should display all the records
Edit
This is my edited portion of numberOfSectionsInTableView and numberOfRowsInSection...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if(searching == YES){
searching = NO;
sectionCount = [tableData count];
}
else {
if(pendingOrder == NO && todaysOrder == NO){
sectionCount = [records count];
NSLog(#"section cout: %d",sectionCount);
}
else if(pendingOrder == YES && todaysOrder == NO){
//Total pending order counting
sectionCount = [pendingRecords count];
NSLog(#"section cout for pending: %d",sectionCount);
}
else if(pendingOrder == NO && todaysOrder == YES){
NSLog(#"todays order number counting");
}
}
return sectionCount;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
Try this:-
copylistofItem is NSMutableArray copying data that matched with search bar criteria.
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
int i=0
for (NSString *str in [records objectAtIndex:indexPath.i] objectAtIndex:0])
{
[searchArray addObject:str];
i++;
}
for (NSString *sTemp in searchArray)
{
NSString *txtToSearch =[[NSString alloc] initWithString:[sTemp substringWithRange:NSMakeRange(0,[searchText length])]];
if([[txtToSearch lowercaseString] isEqualToString:[searchText lowercaseString]])
{
[copyListOfItems addObject:sTemp];
}
}
[searchArray release];
searchArray = nil;
}
Also we want to know what you have written in your numberOfSections tableView Delegate.

iphone: problem reloading table data

I am using custom label in table cell.everytime i visit again this page the label text getting more darker like it is behaving overwriting.
how can i fix this?
- (void)viewWillAppear:(BOOL)animated {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Note" inManagedObjectContext:context];
[request setEntity:entity];
[request release];
[self.tableView reloadData];
}
- (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];
}
// Set up the cell...
Note *noteItem = [resultController objectAtIndexPath:indexPath];
//[cell.textLabel setText:[noteItem noteTitle]];
//[cell.detailTextLabel setText:[dateFormatter stringFromDate:[noteItem creationDate]]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
UILabel *newLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, 200, 19)];
newLabel.text = [noteItem noteTitle];
[newLabel setBackgroundColor:[UIColor clearColor]];
[cell addSubview:newLabel];
[newLabel release];
UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 20, 200, 26)];
detailLabel.text = [dateFormatter stringFromDate:[noteItem creationDate]];
[detailLabel setFont:[UIFont fontWithName:#"Helvetica" size:12.0]];
[detailLabel setBackgroundColor:[UIColor clearColor]];
[cell addSubview:detailLabel];
[detailLabel release];
[cell setBackgroundColor:[UIColor clearColor]];
[cell setAlpha:0.6];
return cell;
}
Create UILabel in
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
and Assign Its Value outside of this condition
your cellForRowAtIndexPath method should look like-
- (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];
nameLabelFrame = CGRectMake(5, 5, 200, 19);
countLabelFrame = CGRectMake(5, 20, 200, 26);
UILabel *lblTemp;
lblTemp = [[UILabel alloc] initWithFrame:nameLabelFrame];
lblTemp.tag = 1;
[cell.contentView addSubview:lblTemp];
[lblTemp release];
lblTemp = [[UILabel alloc] initWithFrame:countLabelFrame];
lblTemp.tag = 2;
[cell.contentView addSubview:lblTemp];
[lblTemp release];
}
// Set up the cell...
Note *noteItem = [resultController objectAtIndexPath:indexPath];
UILabel *newLabel = (UILabel *)[cell viewWithTag:1];
newLabel.text = [noteItem noteTitle];
[newLabel setBackgroundColor:[UIColor clearColor]];
UILabel *detailLabel = (UILabel *)[cell viewWithTag:2];
detailLabel.text = [dateFormatter stringFromDate:[noteItem creationDate]];
[detailLabel setFont:[UIFont fontWithName:#"Helvetica" size:12.0]];
[detailLabel setBackgroundColor:[UIColor clearColor]];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
cell.accessoryView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"]];
[cell setBackgroundColor:[UIColor clearColor]];
[cell setAlpha:0.6];
return cell;
}
You should check if the cell == nil. If so, then add all the labels again, otherwise, they have already been added.