Objective-C: 2 UItableViews displayed - iphone

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)?.

Related

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

Alphabetically sorting the contacts inside a Section header in a UItableview

I have an issue of alphabetically sorting the contacts picked from the address book into section headers . I can arrange them alphabetically without the section headers but how to put them according to the names of the contacts ? I do not want to use the NSDictionary as I am able to do the sorting without it. Please view the code below :-
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [arrayForLastName count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[alphabets sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return [NSArray arrayWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [arrayForLastName count];
}
Any help would be appreciated thanx :)
You can achieve this in following way -
1.Create an index array that contains all the required index -
NSArray *indexArray = [NSArray arrayWithObjects:#"A",#"B",#"C",#"D",#"E",#"F",#"G",#"H",#"I",#"J",#"K",#"L",#"M",#"N",#"O",#"P",#"Q",#"R",#"S",#"T",#"U",#"V",#"W",#"X",#"Y",#"Z", nil];
2.For Each index you need to have an array that will display row for those sections. SO you can have a dictionary that contain an array corresponding to each index.
Check this tutorial, it will help you in implementing this- http://www.icodeblog.com/2010/12/10/implementing-uitableview-sections-from-an-nsarray-of-nsdictionary-objects/
Try this code in table delegate methode.
1) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [dataArray1 count];
}
return number of section in your table view.
2) -(NSMutableArray *)selectedarray:(NSString *)countrynmae
{
NSString *strQuery=[NSString stringWithFormat:#" select * from Globle where Country='%#'",countrynmae];
NSMutableArray *dataarray=[Database executeQuery:strQuery];
return dataarray;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dict =[dataArray1 objectAtIndex:section];
NSString *strcountryname=[dict objectForKey:#"Country"];
NSMutableArray *arr6 = [self selectedarray:strcountryname ];
return [arr6 count];
}
Return number of row in particular section
3) - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// create the parent view that will hold header Label
UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 300.0, 44.0)];
// create the button object
UILabel * headerLabel = [[UILabel alloc] initWithFrame:CGRectZero];
headerLabel.backgroundColor = [UIColor clearColor];
headerLabel.opaque = NO;
headerLabel.textColor = [UIColor whiteColor];
headerLabel.font = [UIFont boldSystemFontOfSize:16];
headerLabel.frame = CGRectMake(20.0, -14.0, 300.0, 30.0);
NSDictionary *dict =[dataArray1 objectAtIndex:section];
headerLabel.text=[dict objectForKey:#"Country"];
headerLabel.textColor=[UIColor redColor];
[customView addSubview:headerLabel];
return customView;
}
set header name for section
4) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.textColor=[UIColor whiteColor];
cell.backgroundColor=[UIColor clearColor];
}
NSDictionary *dict =[dataArray1 objectAtIndex:indexPath.section];
NSString *countryname = [dict objectForKey:#"Country"];
NSString *strQuery = [NSString stringWithFormat:#"Select * from Globle where Country = '%#'",countryname];
NSMutableArray *arr = [Database executeQuery:strQuery];
NSDictionary *dict1 = [arr objectAtIndex:indexPath.row];
cell.textLabel.text=[dict1 objectForKey:#"Name"];
cell.textLabel.numberOfLines=1;
cell.textLabel.textColor=[UIColor blackColor];
cell.backgroundColor=[UIColor clearColor];
cell.textLabel.textAlignment=UITextAlignmentCenter;
NSString *strImage=[dict1 objectForKey:#"ImageName"];
UIImageView *imageView1 = [[UIImageView alloc] init];
UIImage *image1 = [[UIImage alloc] initWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:strImage ofType:#"jpg"]];
imageView1.image = image1;
imageView1.frame = CGRectMake(6,2,50,42); // position it to the middle
[cell.contentView addSubview:imageView1];
return cell;
[tbl reloadData];
}
return cell in uitable view

How to load data in two section of table view 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];
}

Index tableview in iphone sdk

i have an indexed tableview with 8 arrays like
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObject:#"GEN"];
[tempArray addObject:#"1SA"];
[tempArray addObject:#"EST"];
[tempArray addObject:#"EZE"];
[tempArray addObject:#"NAH"];
[tempArray addObject:#"JOH"];
[tempArray addObject:#"COL"];
[tempArray addObject:#"REV"];
return tempArray;
}
and i get everything right,my problem is when i tap the cell it redirected to the another page with only first array value that is the value inside the [tempArray addObject:#"GEN"];and i tap the values in [tempArray addObject:#"1SA"];etc etc,i get the values inn the [tempArray addObject:#"GEN"];.my DidSelectRowAtIndexPath look like this
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ChapterSelectionView *detailViewController = [[ChapterSelectionView alloc] initWithNibName:#"ChapterSelectionView" bundle:nil];
//detailViewController.firstString = firstString;
// ...
// Pass the selected object to the new view controller.
detailViewController.selectedIndex=indexPath.row;
detailViewController.selectedCountry = selectedCountry;
appDelegate.selectedBookIndex=indexPath.row;
self.hidesBottomBarWhenPushed=YES;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
this is my complete tableview code
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return index % 8;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [books count];
}
my viewdidload look like this
- (void)viewDidLoad {
[super viewDidLoad];
l
appDelegate=(Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
s";
books = [[NSMutableArray alloc] init];
NSArray *biblearray1 = [NSArray arrayWithObjects:#"Genesis",
#"Exodus",
#"Leviticus",
#"Numbers",
#"Deuteronomy",
#"Joshua",
#"Judges",
#"Ruth", nil];
NSDictionary *bibledic1 = [NSDictionary dictionaryWithObject:biblearray1 forKey:#"Countries"];
NSArray *biblearray2 = [NSArray arrayWithObjects:#"1Samuel",
#"2Samuel",
#"1King",
#"2King",
#"1Chronicles",
#"2Chronicles",
#"Ezra",
#"Nehemiah", nil];
......etc etc
[books addObject:bibledic1];
[books addObject:bibledic2];
.....etc etc
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary *dictionary = [books objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Countries"];
return [array count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
myBackView.backgroundColor = [UIColor brownColor];
// [myBackView setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:0.75 alpha:1]];
cell.selectedBackgroundView = myBackView;
[myBackView release];
// Configure the cell.
// cell.textLabel.tag =row*1+col;
//First get the dictionary object
NSDictionary *dictionary = [books objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:#"Countries"];
//NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text =[array objectAtIndex:indexPath.row];
cell.textLabel.highlightedTextColor = [UIColor darkGrayColor];
//cell.textLabel.text = [books objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:18.0];
cell.textLabel.textColor = [UIColor darkGrayColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;;
return cell;
}
how to get the correct values from tableview cell.
Thanks in advance.
EDIT
- (void)viewDidLoad {
[super viewDidLoad];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(0,49,320,480)];
appDelegate = (Malayalam_BibleAppDelegate *)[[UIApplication sharedApplication] delegate];
//self.navigationItem.title=[appDelegate.books objectAtIndex:selectedIndex];
chapterlabel.text = [appDelegate.books objectAtIndex:selectedIndex];
buttonArray =[[NSMutableArray alloc]initWithCapacity:0];
//self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg10"]];
[self.view addSubview:scrollView];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
[[self navigationController] setNavigationBarHidden:YES animated:NO];
n=[DbHandler mNumberOfChaptersInBook:[appDelegate.books objectAtIndex:selectedIndex]];
int scrollViewHieght=n/6;
scrollView.contentSize = CGSizeMake(320,10+34*scrollViewHieght);
i=1;
int rowCount=n/6;
for(int row=0;row<=rowCount;row++){
for (int col = 0; col < 6; col++) {
if(i<=n){
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.titleLabel.textColor=[UIColor blueColor];
button.titleLabel.font = [UIFont fontWithName:#"Georgia" size:15.0];
[button setBackgroundImage:[UIImage imageNamed:#"tabs"] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//button.frame=CGRectMake(col*52+5,row*34+50,50,32);
button.frame=CGRectMake(col*52+5,row*34+0,50,32);
[button addTarget:self action:#selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:[NSString stringWithFormat:#"%d",i++] forState:UIControlStateNormal];
//button.titleLabel.font=[UIFont boldSystemFontOfSize:15];
button.titleLabel.textColor=[UIColor blackColor];
button.tag =row*6+col;
[buttonArray addObject:button];
[scrollView addSubview:[buttonArray objectAtIndex:row*6+col]];
//[self.view addSubview:button];
[button release];
}
}
}
}
you also need to send section number to the detailViewController. Depending on the section you have to select the required array.

Crash after returning to tableview

So I am writing an app to read an rss feed, and display the contents in a tableview. It also lets the user play back mp3s that it finds for each item. Anyway the app seemed to be running fine before I started adding new views. Now every time I come back from a view and scroll around a bit, I get "Program received signal "SIGABRT"" or something similar.
here's most of the program:
- (IBAction)playAction:(id)sender
{
// Get row
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *buttonCell =
(UITableViewCell *) [[senderButton superview] superview];
NSInteger buttonRow = [[self.tableView
indexPathForCell:buttonCell] row];
// Entry for row
RSSEntry *senderEntry = [_allEntries objectAtIndex:buttonRow];
// This is where _allEntries gets filled
- (void)requestFinished:(ASIHTTPRequest *)request {
[_queue addOperationWithBlock:^{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil)
{
NSLog(#"Failed to parse %#", request.url);
}
else
{
NSMutableArray *entries = [NSMutableArray array];
[self parseRss:doc.rootElement entries:entries];
if ([_allEntries count] > 0) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Update
int i=0;
while (![[[_allEntries objectAtIndex:i] articleUrl] isEqualToString:[[entries objectAtIndex:i] articleUrl]])
{
[_allEntries insertObject:[entries objectAtIndex:i] atIndex:0];
i++;
}
[self.tableView reloadData];
}];
}
else
{
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries)
{
[_allEntries addObject:entry];
}
NSLog(#"entries:%d", [_allEntries count]);
[self.tableView reloadData];
}];
}
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(#"View did load");
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshButton:)];
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
player = nil;
isPlaying = NO;
self.title = #"Feed";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/"];
[self refresh];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [_allEntries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UILabel *mainLabel, *secondLabel;
UIButton *playBtn;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
mainLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 5.0, 250.0, 20.0)] autorelease];
mainLabel.tag = MAINLABEL_TAG;
mainLabel.font = [UIFont fontWithName:#"Arial-BoldMT" size:18.0];
mainLabel.textAlignment = UITextAlignmentLeft;
mainLabel.textColor = [UIColor blackColor];
mainLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:mainLabel];
secondLabel = [[[UILabel alloc] initWithFrame:CGRectMake(42.0, 27.0, 250.0, 15.0)] autorelease];
secondLabel.tag = SECONDLABEL_TAG;
secondLabel.font = [UIFont fontWithName:#"ArialMT" size:14.0];
secondLabel.textAlignment = UITextAlignmentLeft;
secondLabel.textColor = [UIColor colorWithRed:222.0/255.0 green:95.0/255.0
blue:199.0/255.0 alpha:1.0];
secondLabel.highlightedTextColor = [UIColor whiteColor];
[cell.contentView addSubview:secondLabel];
playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
playBtn.tag = PLAYBTN_TAG;
playBtn.frame = CGRectMake(2.0, 6.0, playImage.size.width, playImage.size.height);
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
//[playBtn setBackgroundImage:playImage forState:UIControlStateHighlighted];
[playBtn addTarget:self action:#selector(playTapped:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:playBtn];
}
else
{
mainLabel = (UILabel *)[cell.contentView viewWithTag:MAINLABEL_TAG];
secondLabel = (UILabel *)[cell.contentView viewWithTag:SECONDLABEL_TAG];
playBtn = (UIButton *)[cell.contentView viewWithTag:PLAYBTN_TAG];
}
// Alternate bg color
if (indexPath.row%2 == 0) {
UIColor *altColor = [UIColor colorWithRed:230.0/255.0 green:230.0/255.0
blue:230.0/255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
else
{
UIColor *altColor = [UIColor colorWithRed:255.0 green:255.0
blue:255.0 alpha:1];
mainLabel.backgroundColor = altColor;
secondLabel.backgroundColor = altColor;
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSLog(#"Entry: %#", entry);
// Manage play button
if (entry == currEntry)
{
if(isPlaying)
{
[playBtn setBackgroundImage:pauseImage forState:UIControlStateNormal];
}
else
{
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
}
}
else
[playBtn setBackgroundImage:playImage forState:UIControlStateNormal];
mainLabel.text = entry.articleTitle;
secondLabel.text = entry.articleArtist;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
DetailView *detailViewController = [[DetailView alloc] initWithNibName:#"DetailedView" bundle:[NSBundle mainBundle]];
RSSEntry *entry = [_allEntries objectAtIndex:[indexPath row]];
[self.navigationController pushViewController:detailViewController animated:YES];
detailViewController.songTitle.text = entry.articleTitle;
detailViewController.artistName.text = entry.articleArtist;
[entry release];
[detailViewController release];
}
- (void)dealloc
{
[player release];
player = nil;
[_queue release];
_queue = nil;
[_feed release];
_feed = nil;
[_allEntries release];
_allEntries = nil;
[super dealloc];
}
#end
Please Dont release any #synthesize variable. You should only release it in dealloc method
It's a wild guess, but you don't retain the images that you get in viewDidLoad:
pauseImage = [UIImage imageNamed:#"pause_circle_small.png"];
playImage = [UIImage imageNamed:#"play_circle_small.png"];
Either use retaining property and dot syntax or send each a retain.
AHAA!!! I was setting my RSSEntry to autorelease before putting them in the _allEntries array. They were getting dealloc'd when I changed views. Don't do that. Thanks for the help everyone. That was so simple, I feel dumb now.
please don't release the self.feed and also when unload or dealloc the view at that time put delegate nil means
tableview.delegate = nil;
this one is the main thing check after this i think u don't nil the delegate of tableview.
without line where you get crash its hard to tell, but most likely you accessing some object what was dealloc'ed
most likely its here
self.feed = [[NSString alloc] initWithString:#"http://site.org/rss/music"];
[self.feed release];
you releasing objects right away, but its hard to tell without knowing if you have retained property