Trouble figuring out the UITableViewCell multiline ability - iphone

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;
}

Related

Table display only 2 labels (out of 4) when use the search Bar

I have a table with 4 labels which works fine. When I use the search bar, which also works fine, the table displays only two labels:
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"airports" ofType:#"json"];
NSString *JSONData = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSArray *airports = [NSJSONSerialization JSONObjectWithData:[JSONData dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
finalArray = [[NSArray alloc]init];
finalArray = airports;
}
-(void)filterContentForSearchText:(NSString *)searchText{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF.airport_name contains[cd] %#", searchText];
self.searchResults = [finalArray filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString{
[self filterContentForSearchText:searchString];
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [finalArray count];
}else{
return [searchResults count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{static NSString *simpleTableIdentifier = #"AirportCell";
AirportCell *cell = (AirportCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AirportCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
NSString *airportName = [[NSString alloc]init];
NSString *iataCode = [[NSString alloc]init];
NSString *icaoCode = [[NSString alloc]init];
NSString *countryAirport = [[NSString alloc]init];
if (tableView == self.tableView) {
airportName = [[finalArray objectAtIndex:indexPath.row] objectForKey:#"airport_name"];
iataCode = [[finalArray objectAtIndex:indexPath.row] objectForKey:#"iata_code"];
icaoCode = [[finalArray objectAtIndex:indexPath.row] objectForKey:#"icao_code"];
countryAirport = [[finalArray objectAtIndex:indexPath.row] objectForKey:#"country"];
cell.iataCodeLabel.text = iataCode;
cell.iataCodeLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.icaoCodeLabel.text = icaoCode;
cell.icaoCodeLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.airportNameLabel.text = airportName;
cell.airportNameLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.countryLabel.text = countryAirport;
cell.countryLabel.font = [UIFont fontWithName:#"Verdana" size:13];
}else{
airportName = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"airport_name"];
iataCode = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"iata_code"];
icaoCode = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"icao_code"];
countryAirport = [[searchResults objectAtIndex:indexPath.row] objectForKey:#"country"];
cell.iataCodeLabel.text = iataCode;
cell.iataCodeLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.icaoCodeLabel.text = icaoCode;
cell.icaoCodeLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.airportNameLabel.text = airportName;
cell.airportNameLabel.font = [UIFont fontWithName:#"Verdana" size:13];
cell.countryLabel.text = countryAirport;
cell.countryLabel.font = [UIFont fontWithName:#"Verdana" size:13];
}
return cell;
}
I believe that your searchDisplayController is altering the height of your cells.
The answer located on this question may be of help to you.
You may find that "AirportCell" is registered only for the main tableview - and not for the search tableview.
[self.searchDisplayController.searchResultsTableView registerClass:[AirportCell class] forCellReuseIdentifier: simpleTableIdentifier];

Looping in UITableViewCell

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

UITableview doubts

i am having an application which can share Notes to evernote,it works fine i can upload and download my Note to Evernote within the app,i have a Note title and Note subject,i uploaded the Notes to evernote viz UITableview controller.The Textlabel.text is the title for the note and detailtextlabel.text is the note subject.i only get the Notesubject correctly means ,if i have two notes in tableview with title,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :secondtitle ,notesubject :secondNotessubject,,then i press the upload button it uploads the notes to evernote,but the title remains firstitle only with notes,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :firsttitle ,notesubject :secondNotessubject.my code for uplode button is
-(IBAction)sendNoteEvernote:(id)sender{
NSMutableString *strtitle = [[NSMutableString alloc] initWithString:#""];
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
NSMutableString *str = [[NSMutableString alloc] initWithString:#"NOTES:"];
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]] ;
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
// Adding the content & resources to the note
[note setContent:ENML];
// [note setTitle:aStringtitle];
// [note setResources:resources];
// Saving the note on the Evernote servers
// Simple error management
#try {
[[eversingleton sharedInstance] createNote:note];
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
}
#catch (EDAMUserException * e) {
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
NSString * errorMessage = [NSString stringWithFormat:#"Error saving note: error code %i", [e errorCode]];
proAlertView *alert = [[proAlertView alloc]initWithTitle:#"Evernote" message:errorMessage delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] withStrokeColor:[UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:1.0]];
[alert show];
[alert release]; return;
}
in the above code appdelegate.indexarray is the title and appdelegate.notearray is the Subject..my UItableview code look like this.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return[appDelegate.notesArray count];
}
/*-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypesForRowWithIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellAccessoryCheckmark;
}*/
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier=[NSString stringWithFormat:#"cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;
UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"bgCELL3#2X-1"]];
[cell setBackgroundView:img];
[img release];
count++;
}
NSMutableString *strr=[[NSMutableString alloc]initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
cell.textLabel.text =strr ;
cell.textLabel.text = [appDelegate.indexArray objectAtIndex:row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.textLabel.textColor = [UIColor brownColor];
//NSMutableString *notes=[[NSMutableString alloc]initWithString:[appDelegate.notesArray objectAtIndex:row]];
//cell.detailTextLabel.text =notes;
cell.detailTextLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.detailTextLabel.textColor = [UIColor darkGrayColor];
cell.detailTextLabel.text = [appDelegate.notesArray objectAtIndex:row];
//textView.text=notes;
//[notes release];
cell.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
whats the error in my code,please help me to do this.
thanks in advance
Try changing the line:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
to:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex: row]];
Also get rid of the:
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier = [NSString stringWithFormat:#"cell %d",indexPath.row];
simply use:
CellIdentifier = #"noteCellIdentifier";
This doesn't have anything to do with your question but it's what cell reusing is all about.
EDIT:
This part of code also looks suspitious:
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
It's not clear what you want to do but you'd probably want to move this to:
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:i]]; //note: t changed to i
note.title =aStringtitle;
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]];
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
//....

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 to fit three labels in a single cell using custom UITableViewCell?

I am customizing my cells and trying to add three labels in a single cell, one on the top and other two in bottom in single line. I am facing some problem wrapping the labels and display the neatly.
Here's the code:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize titleSize = [[[self.titleArray objectAtIndex:indexPath.row] valueForKey:#"display_title"] sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(200, 9999999)
lineBreakMode:UILineBreakModeWordWrap];
CGSize detailSize = [#"APR 21, 2011" sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(200, 999999)
lineBreakMode:UILineBreakModeWordWrap];
CGSize thirdDetailSize = [#"This is the project type." sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(200, 999999)
lineBreakMode:UILineBreakModeWordWrap];
return titleSize.height + MAX (detailSize.height, thirdDetailSize.height) + 15.0;
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel * mainLabel;
UILabel * secondLabel;
UILabel * thirdLabel;
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
NSArray *subviews = cell.contentView.subviews;
for (UIView *vw in subviews)
{
if ([vw isKindOfClass:[UILabel class]])
{
[vw removeFromSuperview];
}
}
mainLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,0,300,22)] ;
mainLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
mainLabel.numberOfLines = 20;
mainLabel.lineBreakMode = UILineBreakModeWordWrap;
mainLabel.backgroundColor = [UIColor clearColor];
mainLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
mainLabel.adjustsFontSizeToFitWidth = YES;
mainLabel.tag = kCellMainLabelTag;
[cell.contentView addSubview:mainLabel];
[mainLabel release];
secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(5,30,140,22)];
secondLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
secondLabel.numberOfLines = 20;
secondLabel.textColor = [UIColor grayColor];
secondLabel.lineBreakMode = UILineBreakModeWordWrap;
secondLabel.backgroundColor = [UIColor clearColor];
secondLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
secondLabel.adjustsFontSizeToFitWidth = YES;
secondLabel.tag = kCellSecondLabelTag;
[cell.contentView addSubview:secondLabel];
[secondLabel release];
thirdLabel = [[UILabel alloc] initWithFrame:CGRectMake(145,30,140,22)];
thirdLabel.font = [UIFont systemFontOfSize:[UIFont smallSystemFontSize]];
thirdLabel.numberOfLines = 20;
thirdLabel.textColor = [UIColor grayColor];
thirdLabel.lineBreakMode = UILineBreakModeWordWrap;
thirdLabel.backgroundColor = [UIColor clearColor];
thirdLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
thirdLabel.adjustsFontSizeToFitWidth = YES;
thirdLabel.tag = kCellSecondLabelTag;
[cell.contentView addSubview:thirdLabel];
[thirdLabel release];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:kCellMainLabelTag];
secondLabel = (UILabel *)[cell.contentView viewWithTag:kCellSecondLabelTag];
thirdLabel = (UILabel *)[cell.contentView viewWithTag:kCellThirdLabelTag];
}
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
NSString * date = [[self.titleArray objectAtIndex:indexPath.row]valueForKey:#"docdt"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
NSDate * intime = [dateFormat dateFromString:date];
NSString * userVisibleDateTimeString;
if (intime != nil) {
// Convert the NSDate to a user-visible date string.
NSDateFormatter * userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:intime];
}
NSString * signDate = userVisibleDateTimeString;
NSArray * parts = [signDate componentsSeparatedByString:#"/"];
NSString * exactFormat = [self displayDate:(NSArray *)parts];
NSString * type = [[self.titleArray objectAtIndex:indexPath.row]valueForKey:#"docty"];
CGSize titleSize = [[[self.titleArray objectAtIndex:indexPath.row] valueForKey:#"display_title"] sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(280, 9999999)
lineBreakMode:UILineBreakModeWordWrap];
CGSize detailSize = [exactFormat sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(200, 999999)
lineBreakMode:UILineBreakModeWordWrap];
CGSize thirdDetailSize = [type sizeWithFont:[UIFont systemFontOfSize:[UIFont smallSystemFontSize]]
constrainedToSize:CGSizeMake(200, 999999)
lineBreakMode:UILineBreakModeWordWrap];
mainLabel.text = [[self.titleArray objectAtIndex:indexPath.row]valueForKey:#"display_title"];
mainLabel.frame = CGRectMake(mainLabel.frame.origin.x,
mainLabel.frame.origin.y, titleSize.width, titleSize.height);
secondLabel.text = exactFormat;
secondLabel.frame = CGRectMake(secondLabel.frame.origin.x,
mainLabel.frame.origin.y + titleSize.height, detailSize.width, detailSize.height);
thirdLabel.text = type;
thirdLabel.frame = CGRectMake(thirdLabel.frame.origin.x,
mainLabel.frame.origin.y + titleSize.height, thirdDetailSize.width, thirdDetailSize.height);
return cell;
}
please help !!!
Thanks,
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 100;}
enter code- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Create
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
//cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
// Configure
switch (indexPath.row) {
case 0:
cell.textLabel.textColor=[UIColor whiteColor];
CGRect myImageRec =CGRectMake(20,20, 50,21 );
UILabel *lbl1=[[UILabel alloc]initWithFrame:myImageRec];
lbl1.text=#"label1";
[ cell addSubview: lbl1];
CGRect frame1=CGRectMake(20,49, 50,21 );
UILabel *lbl2=[[UILabel alloc]initWithFrame:frame1];
lbl2.text=#"label2";
[ cell addSubview: lbl2];
CGRect frame2=CGRectMake(20,73, 50,21 );
UILabel *lbl3=[[UILabel alloc]initWithFrame:frame2];
lbl3.text=#"label3";
[ cell addSubview: lbl3];
break;
default: break;
}
return cell;
}
I have use this and i display three label in one cell i show also image of output.