How to load data in two section of table view iPhone - iphone

I have 2 sections within a table view and I have loaded one section from one array and one from another. How can I set cell values for both sections?
I'm using the following code:
Title For Header Section.
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section
{
if(section == 0)
return #" Scheduled Patients ";
else
return #" Walk In Patients ";
}
Rows in Section:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(section==0)
return [resultArray count];
else {
EMRAppDelegate *appDelegate = (EMRAppDelegate *)[[UIApplication sharedApplication] delegate];
return [appDelegate.walkPatients count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIButton * uploadButton = nil;
static NSString * Identifier = #"Identifier";
UITableViewCell * cell = [table dequeueReusableCellWithIdentifier:Identifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:Identifier] autorelease];
uploadButton = [UIButton buttonWithType:UIButtonTypeCustom];
[uploadButton setFrame:CGRectMake(10, 10, 24, 24)];
[uploadButton setImage:[UIImage imageNamed:#"upload.png"] forState:UIControlStateNormal];
[uploadButton addTarget:self action:#selector(onUploadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
[uploadButton setTag:999];
cell.accessoryView = uploadButton;
}
else {
uploadButton = (UIButton *)cell.accessoryView;
}
EMRAppDelegate *appDelegate = (EMRAppDelegate *)[[UIApplication sharedApplication] delegate];
ObjectData *theCellData =[resultArray objectAtIndex:indexPath.row];
WalkPatient * patient = [ appDelegate.walkPatients objectAtIndex:indexPath.row];
if (indexPath.section == 0)
{
// do coding for cell loading for Scheduled Patients
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", theCellData.firstName, theCellData.lasttName];
if (patient.syncDate != nil) {
UIImageView * checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"right.png"]];
[checkmark setFrame:CGRectMake(12, 0, 12, 12)];
[checkmark setTag:998];
[uploadButton addSubview:checkmark];
[checkmark release];
[uploadButton removeTarget:self action:#selector(onUploadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy hh:mm"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Synched: %#", [dateFormatter stringFromDate:patient.syncDate]];
[dateFormatter release];
}
else {
UIView * checkmark = (UIView *)[uploadButton viewWithTag:998];
if (checkmark != nil) {
[checkmark removeFromSuperview];
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
else
{
// do load cells for Walk In Patients.
cell.textLabel.font = [UIFont systemFontOfSize:18];
cell.textLabel.text = [NSString stringWithFormat:#"%# %#", patient.firstName, patient.lastName];
if (patient.syncDate != nil) {
UIImageView * checkmark = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"right.png"]];
[checkmark setFrame:CGRectMake(12, 0, 12, 12)];
[checkmark setTag:998];
[uploadButton addSubview:checkmark];
[checkmark release];
[uploadButton removeTarget:self action:#selector(onUploadButtonClick:) forControlEvents:UIControlEventTouchUpInside];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy hh:mm"];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12];
cell.detailTextLabel.text = [NSString stringWithFormat:#"Synched: %#", [dateFormatter stringFromDate:patient.syncDate]];
[dateFormatter release];
}
else {
UIView * checkmark = (UIView *)[uploadButton viewWithTag:998];
if (checkmark != nil) {
[checkmark removeFromSuperview];
}
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
}

Its simple. In cellForRowAtIndexPath method also you put one condition to check the section and load data according to them.
if (indexPath.section == 0)
{
// do coding for cell loading for Scheduled Patients
UIButton *btnsection0=[UIButton buttonWithType:UIButtonTypeCustom];
[btnsection0 addTarget:self action:#selector(showProject:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
// do load cells for Walk In Patients.
UIButton *btnsection1=[UIButton buttonWithType:UIButtonTypeCustom];
[btnsection0 addTarget:self action:#selector(showProject:) forControlEvents:UIControlEventTouchUpInside];
}

You've almost got it. The cellForRowAtIndexPath method comes with an indexPath parameter that can give you:
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
Please, always, always make cellForRowAtIndexPath logic mirror the numberOfRowsInSection logic, so when you get asked for a row count:
return (section==0)? [array0 count] : [array1 count];
... and when you get asked for a cell, and you need the data for that cell
NSInteger row = indexPath.row;
NSInteger section = indexPath.section;
NSArray *arrayForThisSection = (section==0)? array0 : array1;
id elementForThisRow = [arrayForThisSection objectAtIndex:row];
// config the cell with elementForThisRow

From the documentation for UITableViewDataSource:
UITableView declares a category on NSIndexPath that enables you to get the represented row index (row property) and section index (section property),
So you can go indexPath.section and it'll tell you which section the tableview wants to populate.

UIButton *btnsection0=[UIButton buttonWithType:UIButtonTypeCustom];
if (indexPath.section == 0)
{
btnsection0.tag = [NSString stringWithFormat:#"%d%d",indexPath.section,indexPath.row];
}else{
btnsection0.tag = [NSString stringWithFormat:#"%d%d",indexPath.section,indexPath.row];
}
[btnsection0 addTarget:self action:#selector(showProject:) forControlEvents:UIControlEventTouchUpInside];
button event
-(IBAction)showProject:(id)sender{
NSString *s = [NSString stringWithFormat:#"%d%d",indexPath.section,indexPath.row];
int section = [[s substringToIndex:1] intValue];
int row = [[s substringFromIndex:0] intValue];
}

Related

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

Insert NSarray items into specified UItableviewcell

I have a UItableview with 10 cells.I need to display a message from an NSarray into this tableview.The array contains 3 items and needs to be displayed in the any of the 3 cells .
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
CustomTableView *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[ CustomTableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSString *order = [orderArray objectAtIndex:indexPath.row];
NSString *sdate = [dateArray objectAtIndex:indexPath.row];
//Label positions
UILabel *ordernum = [[UILabel alloc] initWithFrame:CGRectMake(5,28,95,21)];
UILabel *date = [[UILabel alloc] initWithFrame:CGRectMake(100,28,80,21)];
UILabel *orderStatusMessage = [[UILabel alloc] initWithFrame:CGRectMake(200,28,80,21)];
NSString *ordertypeName = [ordertypeArray objectAtIndex:indexPath.row];
ordernum.textColor = [UIColor blackColor];
[cell.contentView addSubview:ordernum];
date.textColor = [UIColor blackColor];
[cell.contentView addSubview:date];
orderStatusMessage.textColor = [UIColor blackColor];
if ([ordertypeName isEqualToString:#"saved"]) {
ordernum.text = [NSString stringWithString:#"Saved Order"];
date.text = [NSString stringWithFormat:#"%#",sdate];
}
else{
if (![order isEqualToString:#""]) {
for (int i=0; i<[reversed count]; i++)
{
stat=[reversed objectAtIndex:i];
}
}
ordernum.text = [NSString stringWithFormat:#"%#",order];
date.text = [NSString stringWithFormat:#"%#",sdate];
orderStatusMessage.text =[NSString stringWithFormat:#"%#",stat];
[cell.contentView addSubview:orderStatusMessage];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.selectionStyle = UITableViewCellSelectionStyleGray;
// }
return cell;
}
With the above code I am getting only the last item from reversed array.Please help
To start, your for loop is bogus
if (![order isEqualToString:#""]) {
for (int i=0; i<[reversed count]; i++)
{
stat=[reversed objectAtIndex:i];
}
}
Why are you looping and overwriting the reference to stat with each iteration? That's clearly not your intent.
Second, I would advise refactoring, since this code snippit is extremely confusing and it is very close to impossible to understand the intent. Please repost after renaming variables and cleaning the code a bit.

Objective-C: 2 UItableViews displayed

I am sorry for pasting a big chunk of code but i really want to get it work;
This app is supposed to be placing a UItableView on a screen.
Somehow this code is calling tableview methods twice and creating duplicate tables.
Do you have any suggestion what I can do to fix this behaviour?
Thanks in advance.
UITableView:
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"-------------numberOfRowsInSection---------------");
NSLog(#"qtext =%d",[qtext count]);
return [qtext count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
return 1;
}
-(void)insertDeviders{
UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 100)];
myLabel.text = #"About you";
[cell addSubview:myLabel];
}
//Return cellheight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSLog(#"-------------heightforrowatindexpath---------------");
dict = [qtext objectAtIndex:[indexPath row]];
NSDictionary *dict2 = [qtype objectAtIndex:[indexPath row]];
type = [[dict2 allKeys] objectAtIndex:0];
NSString *text = [[dict allKeys] objectAtIndex:0];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
CGFloat height = MAX(size.height, 44.0f);
thisheight= height + (CELL_CONTENT_MARGIN * 2) + 40;
NSLog(#"thisheight=%d",thisheight);
NSString *q = [NSString stringWithFormat:#"%d", thisheight];
[arrAllheight addObject:[NSString stringWithFormat:#"%#",q]];
if([type isEqualToString:#"devider"]){thisheight=28;}
NSLog(#"dict=%#",dict);
NSLog(#"thisheight=%d",thisheight);
return thisheight;
}
Populate cell:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"-------------cellForRowAtIndexPath---------------");
cell_id = [qid objectAtIndex:[indexPath row] ];
static NSString *CellIdentifier = #"Cell";
label = nil;
cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// if(![cell_id intValue]==0){
dict = [qtext objectAtIndex:[indexPath row]];
celltext = [NSString stringWithFormat:#"%#\n\n\n",[[dict allKeys] objectAtIndex:0]];
dict = [qtype objectAtIndex:[indexPath row]];
type = [[dict allKeys] objectAtIndex:0];
//place the question
cell.textLabel.text = celltext;
// NSLog(#"row=%#",[indexpath row]);
if([type isEqualToString:#"devider"]){
[self configureDevider];
}else{
[self configureCell];
}
if([cell_id intValue] == ([qid count])){
tabledone = #"Yes";
}
tableView.backgroundColor=[UIColor clearColor];
tableView.opaque=NO;
tableView.backgroundView=nil;
NSString *a = [arrAllheight objectAtIndex:[indexPath row]];
// NSLog(#"allheight=%d",allheight);
allheight +=thisheight;
thisheight =[a intValue];
if(![tabledone isEqualToString:#"Yes"])
if([type isEqualToString:#"YN"]){
DCRoundSwitch *ynSwitch = [[DCRoundSwitch alloc] initWithFrame:CGRectMake(220,thisheight-40,80,27)] ;
ynSwitch.onText=#"Yes";
ynSwitch.offText=#"No";
[answers addObject:ynSwitch];
[cell addSubview:ynSwitch];
[ynSwitch setTag:[cell_id intValue]];
[ynSwitch addTarget:self action:#selector(setAnswersForRoundSwitches:) forControlEvents:UIControlEventValueChanged];
NSLog(#"cell_id=%#", [dicAnswers objectForKey:[NSString stringWithFormat:#"", cell_id]]);
// if[dicAnswers objectForKey:[NSString stringWithFormat:#"", cell_id]]){}
i++;
}else if([type isEqualToString:#"freetext"]){
//When the done button was clicked, remove the keybords from the screen
[self makeTextField];
[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
// [rtxtfield value];
}else if([type isEqualToString:#"dropdown"]){
picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:#"%d",cell_id]];
//Choose an array for this textField
// [self getPickerArray];
[self makeTextField];
//[rtxtfield addTarget:self action:#selector(setAnswersfortextFields:) forControlEvents:UIControlEventEditingDidEndOnExit];
//When the done button was clicked, remove the keybords from the screen
[rtxtfield addTarget:self action:#selector(textFieldReturn:) forControlEvents:UIControlEventEditingDidEndOnExit];
//Get the tag for picker
[rtxtfield addTarget:self action:#selector(getTag:) forControlEvents:UIControlEventTouchDown];
//Display picker
[rtxtfield addTarget:self action:#selector(acsheet:) forControlEvents:UIControlEventTouchDown];
//set Tag for the textField
[rtxtfield setTag:[cell_id intValue]];
NSLog(#"rtxtfield tag=%d",rtxtfield.tag);
}
if([type isEqualToString:#"devider"]){
[self caliculateHeightofCell];
}else{
[self caliculateHeightofCell];
}
return cell;
}
get tag name when user finished editing:
-(void)getTag:(UITextField*)txtf{
NSLog(#"-------------getTag-------------");
whichTextTag = txtf.tag;
picc = [picker_array objectForKey:[[NSString alloc] initWithFormat:#"%d",whichTextTag]];
[self getPickerArray];
}
lifecycle:
- (void)viewDidLoad
{
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"main_bg.png"]];
// [super viewDidLoad];
dicAnswers = [NSMutableDictionary dictionary];
[self getClaimQuestions];
[self getSchemeLimitThreshold];
[self getShchemeLimit];
tabledone=#"";
[self getQuestionsAY];
// [self getQuestionsH];
[self getCountries];
// [self getQuestions];
[self getITClass];
self->table.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
self->table.separatorColor = [UIColor lightGrayColor];
[self placeNextButton];
// tabledone =#"Yes";
}
Are you using interface builder? Then check if you have not connected the tableview to the controller twice in IB - once as the view outlet and again as table.
I haven't tested your code as I don't have your data nor do I see how it's being built but looking through your code I see several problems. The most dire one though is you may not understand how dequeueReusableCellWithIdentifier is supposed to work. You appear to be defining the variable cell outside of your tableView:cellForRowAtIndexPath: which means that you could be overwriting that cell every time. I'd suggest you read up on how the dequeueReusableCellWithIdentifier is supposed to work. Have a look here: iPhone - What are reuseIdentifiers (UITableViewCell)?.

tableview refreshing while searching on iphone

I have a table view that shows 3 data side by side in table ,lets say A(name) , B(roll no) , C(id).
Now if user do search based on A's (search by name) (table get refreshed with name while searching only) value I want to either hide the content of B & C or they should show the correct value while search is on , not the old value which they got before searching.
I couldn't find the solution how to deal with remaining B & C.kindly suggest
here is my code
- (void) searchTableView
{
NSLog(#"search button is down %#",searchBar.text);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
if(SearchQuery==1)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"Name"]];
}
if(SearchQuery==2)
{
[searchArray addObjectsFromArray:[entityArray valueForKey:#"IC"]];
}
for (NSString *sTemp in searchArray)
{
NSLog(#"copyListOfItems in search -%#",copyListOfItems);//final array for names
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = (NSManagedObject *)[entityArray objectAtIndex:indexPath.row];
NSString *CellIdentifier = #"Cell";
int indicator = UITableViewCellAccessoryNone;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 50.0)] autorelease];//220
mainLabel.tag = MAINLABEL_TAG;
[mainLabel setFont:[UIFont fontWithName:#"Helvetica-Bold" size:18]];//Palatino-BoldItalic
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(313.0, 9.0, 200.0, 25.0)] autorelease];//83
secondLabel.tag = SECONDLABEL_TAG;
smallSystemFontSize]]];
[secondLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:secondLabel];
//// 3rd labl display
thirdLabel = [[[UILabel alloc] initWithFrame:CGRectMake(560.0, 9.0, 250.0, 25.0)] autorelease];//83
thirdLabel.tag = THIRDLABEL_TAG;
//thirdLabel.font = [UIFont systemFontOfSize:13.0];
[thirdLabel setFont:[UIFont fontWithName:#"Helvetica" size:18]];//Palatino-BoldItalic
thirdLabel.textAlignment = UITextAlignmentLeft;
thirdLabel.textColor = [UIColor blackColor];
[cell.contentView addSubview:thirdLabel];
}
if(searching)
{
NSLog(#" seacrh List in table view =%#",[copyListOfItems objectAtIndex:indexPath.row]);
// NSString *s=[object valueForKey:#"Name"];
NSLog(#"copyListOfItems length ---------%d",[copyListOfItems count]);
cell.textLabel.text =[copyListOfItems objectAtIndex:indexPath.row] ;
if(SearchQuery==2)
{
secondLabel.text=#"kk";// not working
secondLabel.alpha=1; // this is not working i cant upadate
}
}
else
{
if(self.entityName == #"Parent")
{
{
indicator = UITableViewCellAccessoryDisclosureIndicator;
CellIdentifier = #"CellWithDisclosure";
}
}
if(SearchQuery==2)
{
cell.textLabel.text =[object valueForKey:#"IC"] ;
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
thirdLabel = (UILabel *)[cell.contentView viewWithTag:THIRDLABEL_TAG];
NSLog(#"sex is %# ",[object valueForKey:#"Name"]);
secondLabel.text=[object valueForKey:#"Name"] ;
secondLabel.alpha=0;
thirdLabel.text=[object valueForKey:#"roll"] ;
}

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.