Looping in UITableViewCell - iphone

I m doing a quiz project where the number of questions and number of options for a questions are dynamic (taken from a service url).Maximum 5 options for a question(but may be decreased).I m displaying it in sectioned UITableView where each question and its options are displayed in one section.I m taking the objects in one section in a NSMutableArray and looping the options each time .But Im getting only the last option.
I couldnot understand why is it so ?
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *hlCellID=#"hlCellID";
UITableViewCell* hlcell=[tableView dequeueReusableCellWithIdentifier:hlCellID];
if(hlcell == nil)
{
hlcell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:hlCellID]autorelease];
hlcell.accessoryType = UITableViewCellAccessoryNone;
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
lblQuestion = [[UILabel alloc] initWithFrame:CGRectZero];
lblQuestion.tag = 1;
lblQuestion.backgroundColor = [UIColor clearColor];
[lblQuestion setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[lblQuestion setLineBreakMode:NSLineBreakByWordWrapping];
[hlcell addSubview:lblQuestion];
lblanswers = [[UILabel alloc] initWithFrame:CGRectZero];
lblanswers.tag = 2;
lblanswers.backgroundColor = [UIColor clearColor];
[lblanswers setFont:[UIFont fontWithName:#"Helvetica-Bold" size:12]];
[lblanswers setLineBreakMode:NSLineBreakByWordWrapping];
[hlcell addSubview:lblanswers];
}
int section=indexPath.section;
NSMutableArray *sectionItems=[self.finalarray objectAtIndex:indexPath.section];
int n=[sectionItems count];
hlcell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString *question = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:indexPath.row] objectForKey:#"Question"]];
CGSize constraint1 = CGSizeMake(320, 2000.0f);
CGSize size1 = [question sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint1 lineBreakMode:NSLineBreakByWordWrapping];
lblQuestion = (UILabel *)[hlcell viewWithTag:1];
lblQuestion.text = [NSString stringWithFormat:#"%#",question];
[lblQuestion setNumberOfLines:0];
lblQuestion.frame = CGRectMake(10,25, size1.width, size1.height);
for(int j=1;j<n;j++)
{
NSLog(#"%#",[[sectionItems objectAtIndex:j] objectForKey:#"Description"]);
NSString *answer = [NSString stringWithFormat:#"%#",[[sectionItems objectAtIndex:j] objectForKey:#"Description"]];
CGSize constraint2 = CGSizeMake(320, 2000.0f);
CGSize size2 = [answer sizeWithFont: [UIFont fontWithName:#"Helvetica-Bold" size:14] constrainedToSize:constraint2 lineBreakMode:NSLineBreakByWordWrapping];
lblanswers = (UILabel *)[hlcell viewWithTag:2];
lblanswers.text = [NSString stringWithFormat:#"%#",answer];
[lblanswers setNumberOfLines:0];
lblanswers.frame = CGRectMake(10,20*j, size2.width, size2.height);
[hlcell.contentView addSubview:lblanswers];
}
return hlcell;
}
I couldn't understand how to set the frame for a lblanswers.
EDIT:
-(IBAction)checkboxClicked:(id)sender
{
NSMutableArray *arr1=[[NSMutableArray alloc]init];
NSIndexPath *indexPath = [self.tableView indexPathForCell:(UITableViewCell *)
[[sender superview] superview]];
NSLog(#"The section is %d", indexPath.section);
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSMutableArray *cellSection = [self.finalarray objectAtIndex:indexPath.section];
int tagID=[sender tag];
int divnum=0;
if(tagID<100)
divnum=10;
else
divnum=100;
int section=[sender tag]/divnum;
section-=1;
int itemId=[sender tag]%divnum;
if(itemId==selectedrowforCheckBox)
{
if(self.isChecked ==NO)
{
self.isChecked =YES;
[sender setImage:[UIImage imageNamed:#"checkbox_checked.png"] forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
NSMutableDictionary *hk=[[NSMutableDictionary alloc]init];
[hk setObject:xWrapped forKey:#"Ans"];
[hk setObject:questionId forKey:#"QId"];
[selectedOptionandQIdArray addObject:hk];
}
else
{
self.isChecked =NO;
[sender setImage:[UIImage imageNamed:#"checkbox_unchecked.png"]forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
for (int i=0;i<[selectedOptionandQIdArray count];i++)
{
NSString *qid=[[selectedOptionandQIdArray objectAtIndex:i]objectForKey:#"QId"];
if(xWrapped==[[selectedOptionandQIdArray objectAtIndex:i]objectForKey:#"Ans"] && [questionId isEqualToString:qid])
{
NSLog(#"nnd");
[selectedOptionandQIdArray removeObjectAtIndex:i];
}
}
}
selectedrowforCheckBox=itemId;
}
else
{
if(self.isChecked ==NO)
{
self.isChecked =YES;
[sender setImage:[UIImage imageNamed:#"checkbox_checked.png"] forState:UIControlStateNormal];
NSNumber* xWrapped = [NSNumber numberWithInt:itemId];
int m=[cellSection count]-1;
NSString *questionId=[[cellSection objectAtIndex:m-1]objectForKey:#"QId"];
NSMutableDictionary *hk=[[NSMutableDictionary alloc]init];
[hk setObject:xWrapped forKey:#"Ans"];
[hk setObject:questionId forKey:#"QId"];
[selectedOptionandQIdArray addObject:hk];
}
else
{
self.isChecked =NO;
[sender setImage:[UIImage imageNamed:#"checkbox_unchecked.png"]forState:UIControlStateNormal];
}
selectedrowforCheckBox=itemId;
}
}

You are doing it wrong. Break down the work in to two parts:
Before that create a dictionary in which each key is question and associated object is an array which contains all the answers.
number of sections = [dictionary count]
number of rows per section = [[dictionary valueForKey:[[dic allKeys] objectAtIndex:indexPath.section]] count]
Questions - create a custom view with UITextView and return that as header for each section and you can adjust the height by calculating and returning height based on question.
Answers - create a custom cell with UITextView and set the text based on section and row.
This strategy will not only simplify the code by given it a structure but also specify the detection of answers selected by user, as you can just store indexPath and check the section for question and row for answer selected by user.
U can download a sample code from here: http://www.saplogix.net/QA/sample.zip

Related

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.

UITableView throws EXEC_BAD_ACCESS when user tries to scroll to reveal lower rows

My UITableView is displaying correctly without a hitch. However, it crashes with EXEC_BAD_ACCESS whenever the user tries to scroll down to reveal the bottom rows. I have already tried commenting out every [someobject release] but to no avail. I suspect the culprit is the cellForRowAtIndexPath method. Here is the code for my entire controller :
-(void)viewDidLoad {
NSLog(#"myString is :%#", myString);
int processID = [myString intValue];
//NSLog(#"transferredArray is %#", transferredArray);
task = [[NSTask alloc] init];
[task setLaunchPath: #"/bin/ps"];
arguments = [NSArray arrayWithObjects: #"aux", [NSString stringWithFormat:#"%i", processID],nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSLog(#"ps aux output :%#",string);
NSArray *lines= [string componentsSeparatedByString:#"\n"];
NSString *lastline = [lines objectAtIndex:[lines count]-2];
// NSLog(#"%#",lastline);
lines2= [lastline componentsSeparatedByString:#" "];
NSLog(#"%#",lines2);
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#""]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#""]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#""""]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#"0"]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#"0.0"]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#"??"]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#"0:00.00"]){
[lines2 removeObjectAtIndex:i];
}
}
NSLog(#"lines2 after for loops is %#", lines2);
NSLog(#"Lines 2 is%#",lines2);
self.title = #"Process Info";
label = [[NSMutableArray alloc]init];
[label addObject:#"User:"];
[label addObject:#"Process ID:"];
[label addObject:#"CPU(%):"];
[label addObject:#"MEM(%):"];
[label addObject:#"Status:"];
[label addObject:#"Time Started:"];
[label addObject:#"Launch Path:"];
[label addObject:#"STAT:"];
[label addObject:#"Time Started:"];
[label addObject:#"Time Elapsed:"];
[label addObject:#"Launch Command:"];
[super viewDidLoad];
}
/*
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
*/
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
/*
NSString *CellIdentifier = [NSString stringWithFromat:#"Cell_%d_%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
*/
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
NSString *cellValue = [label objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
cell.textColor = [UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1];
cell.font = [UIFont systemFontOfSize:16.0];
UILabel *label2 = [[[UILabel alloc] initWithFrame:CGRectMake(120.0, 0, 240.0,
tableView.rowHeight)]autorelease];
label2.font = [UIFont systemFontOfSize:16.0];
NSString *cellValue1 = [lines2 objectAtIndex:indexPath.row];
label2.text = cellValue1;
label2.textAlignment = UITextAlignmentLeft;
label2.textColor = [UIColor blackColor];
label2.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label2];
return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [lines2 count];
}
- (void)dealloc
{
//[transferredArray release];
//[myString release];
//[arguments release];
//[ResultStringID release];
//[values release];
//[label release];
[super dealloc];
}
Any help is very much appreciated! :)
i think this will help:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *label2;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.textColor = [UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1];
cell.font = [UIFont systemFontOfSize:16.0];
label2 = [[[UILabel alloc] initWithFrame:CGRectMake(120.0, 0, 240.0,
tableView.rowHeight)]autorelease];
label2.font = [UIFont systemFontOfSize:16.0];
NSString *cellValue1 = [lines2 objectAtIndex:indexPath.row];
label2.text = cellValue1;
label2.textAlignment = UITextAlignmentLeft;
label2.textColor = [UIColor blackColor];
label2.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label2];
}
NSString *cellValue = [label objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
because you tablecell is dequeueble so you shoulden't init label if cell is not nil. only change text of the label when tableview is updated (or init everything if cell is nil)

Trouble figuring out the UITableViewCell multiline ability

Got pretty far with this one but am hanging on the part where I read out the string information.
I made a cell that receives data from an external xml file, it all works fine but some cell contain to much text which I want to display over multiple lines. Also no problem. But the tricky part is the dynamic height of my cell. I configured this in the heightForRowAtIndexPath: method, but I need to know the amount of text(rows) the cell contains, and I am stuck on the part how to connect that to my cellText(string) variable.
Any help would be welcome :-)
Here is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
// Set the text in the cell for the section/row.
NSString *endDate = [XMLParser stringFromDate:[XMLParser dateFromString:stage.end]];
int endDateLength = endDate.length;
NSString *endTime = [NSString stringWithFormat:#"%#", [endDate substringFromIndex:endDateLength -7]];
NSString *startDate = [XMLParser stringFromDate:[XMLParser dateFromString:stage.start]];
int startDateLength = startDate.length;
NSString *startTime = [NSString stringWithFormat:#"%#", [startDate substringFromIndex:startDateLength -7]];
NSString *date = [XMLParser stringFromDate:[XMLParser dateFromString:stage.start]];
int dateLength = date.length;
NSString *dateString = [NSString stringWithFormat:#"%#", [date substringToIndex:dateLength -7]];
NSString *cellText = nil;
NSString *cellExplainText = nil;
//Pre title arrays
dateTitleArray = [[NSArray alloc] initWithObjects:#"Dag", #"Start tijd", #"Eind tijd", nil];
nameTitleArray = [[NSArray alloc] initWithObjects:#"Naam", #"Graad",nil];
addressTitleArray = [[NSArray alloc] initWithObjects:#"Dojo", #"Straat", #"Plaats",nil];
infoTitleArray = [[NSArray alloc] initWithObjects:#"Kosten", #"Contact", #"Details", nil];
dateArray = [[NSArray alloc] initWithObjects: dateString, startTime, endTime, nil];
nameArray = [[NSArray alloc] initWithObjects: stage.teacher, stage.grade, nil];
addressArray = [[NSArray alloc] initWithObjects: stage.dojo, stage.street, stage.city, nil];
infoArray = [[NSArray alloc] initWithObjects: stage.cost, stage.contact, stage.details, nil];
switch (indexPath.section)
{
case 0:
cellExplainText = [dateTitleArray objectAtIndex:indexPath.row];
cellText = [dateArray objectAtIndex:indexPath.row];
break;
case 1:
cellExplainText = [nameTitleArray objectAtIndex:indexPath.row];
cellText = [nameArray objectAtIndex:indexPath.row];
break;
case 2:
cellExplainText = [addressTitleArray objectAtIndex:indexPath.row];
cellText = [addressArray objectAtIndex:indexPath.row];
break;
case 3:
cellExplainText = [infoTitleArray objectAtIndex:indexPath.row];
cellText = [infoArray objectAtIndex:indexPath.row];
break;
default:
break;
}
[dateTitleArray release];
[nameTitleArray release];
[addressTitleArray release];
[infoTitleArray release];
[dateArray release];
[nameArray release];
[addressArray release];
[infoArray release];
cell.textLabel.text = cellExplainText;
cell.detailTextLabel.text = cellText;
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.font = [UIFont fontWithName:#"Helvetica" size:14.0];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellTextSize = ????????????;
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellTextSize sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 12;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGSize maxSize = CGSizeMake(urMaxSize);
CGSize cellSize = [itemName sizeWithFont:[UIFont systemFontOfSize:15]
constrainedToSize:maxSize lineBreakMode:UILineBreakModeWordWrap];
return cellSize.height;
}
itemName is the text u want to fill it with. I guess it is [infoTitleArray objectAtIndex:indexPath.row] and corresponding array information based on index. You can get the section also in this method so you can get the string.
If you want to use your method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellText;
switch (indexPath.section)
{
case 0:
cellText = [dateTitleArray objectAtIndex:indexPath.row];
break;
case 1:
cellText = [nameTitleArray objectAtIndex:indexPath.row];
break;
case 2:
cellText = [addressTitleArray objectAtIndex:indexPath.row];
break;
case 3:
cellText = [infoTitleArray objectAtIndex:indexPath.row];
break;
default:
break;
}
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 12;
}
I would suggest you to store in an array your cellText/cellTextExplained values, so that in heightForRowAtIndexPath: you can retrieve them:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
NSString *cellText = [self.cellTextArray:objectAtIndex:indexPath.row];
//-- rest of your code here
UIFont *cellFont = [UIFont fontWithName:#"Helvetica" size:14.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellTextSize sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 12;
}