iphone:UItableviewcell duplicates when using table reload - iphone

My tableview gets duplicated when I use [tableview reloadData].I used this to refresh the tableview when I move back.How could I overcome the issue?
This is my code.
#define kMyTag 1
#define despTag 2
#define subTag 3
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.tableview reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
AsyncImageView *asyncImageView = nil;
UILabel *label = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] ;
UILabel *mainLabel=[[UILabel alloc]init];
mainLabel.tag = kMyTag; // define kMyTag in your header file using #define
mainLabel.frame=CGRectMake(95, 0, 170, 30);
mainLabel.font = [UIFont boldSystemFontOfSize:14];
mainLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:mainLabel];
UILabel *despLabel=[[UILabel alloc]init];
despLabel.tag=despTag;
despLabel.frame=CGRectMake(95, 25, 190, 20);
despLabel.font= [UIFont systemFontOfSize:12];
despLabel.backgroundColor=[UIColor clearColor];
[cell.contentView addSubview:despLabel];
} else {
label = (UILabel *) [cell.contentView viewWithTag:LABEL_TAG];
}
switch([indexPath section]){
case 0:
{
NSString *urlString = [img objectAtIndex:indexPath.row];
urlString=[urlString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
tname=[mname objectAtIndex:indexPath.row];
tprice=[mprice objectAtIndex:indexPath.row];
tquan=[mquan objectAtIndex:indexPath.row];
tspice=[mspice objectAtIndex:indexPath.row];
UILabel *mainLabel=(UILabel *)[cell.contentView viewWithTag: kMyTag];
mainLabel.text = [NSString stringWithFormat:#"%#",tname];
UILabel *despLabel=(UILabel *)[cell.contentView viewWithTag: despTag];
despLabel.text = [NSString stringWithFormat:#"Qty :%# Spice: %#",tquan,tspice];
UILabel *subLabel=(UILabel *)[cell.contentView viewWithTag: subTag];
float pric=[tprice floatValue];
subLabel.text = [NSString stringWithFormat:#"Price :%# %.2f",currencyType, pric];
}
}
}

Overcomes the issue by removing all the objects from array,then reselects the DB table & reloads uitableview.

it happens because you are not passing any value in dequeueReusableCellWithIdentifier
pass a string value and then use it in reuseIdentifier also

Related

Load more at the top of uitableview

I need a load more cell at the top of my table populated with custom cell, the first time that I populate the table is all ok, no overlap and no problem, if I try to load more cell this cell appear but with the wrong height and if I try to scroll the cell change position randomly!
This is my code, where the mistake for you?
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.arrayMessaggi count] + 1;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (indexPath.row == 0) {
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *labelLoad = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
[labelLoad setBackgroundColor:[UIColor clearColor]];
[labelLoad setTextAlignment:NSTextAlignmentCenter];
[labelLoad setText:[NSString stringWithFormat:#"%d - Load more...",indexPath.row]];
[labelLoad setText:#"Load more..."];
[labelLoad setTag:3];
[cell.contentView addSubview:labelLoad];
}
UILabel *labelLoad = (UILabel *)[cell.contentView viewWithTag:3];
[labelLoad setText:[NSString stringWithFormat:#"%d - Load more...",indexPath.row]];
}
else {
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
PFUser *user = [obj objectForKey:#"daUtente"];
float height = [self getStringHeight:[obj objectForKey:#"TestoMessaggio"] andFont:[UIFont systemFontOfSize:13]];
UILabel *labelUser = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 280, 20)];
[labelUser setBackgroundColor:[UIColor clearColor]];
[labelUser setText:[user objectForKey:#"username"]];
[labelUser setFont:[UIFont systemFontOfSize:13]];
[labelUser setTag:1];
[cell.contentView addSubview:labelUser];
}
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
PFUser *user = [obj objectForKey:#"daUtente"];
UILabel *labelUser = (UILabel *)[cell.contentView viewWithTag:1];
[labelUser setText:[NSString stringWithFormat:#"%d - %#",indexPath.row,[user objectForKey:#"username"]]];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
float height = 44;
if (indexPath.row > 0) {
PFObject *obj = [self.arrayMessaggi objectAtIndex:indexPath.row - 1];
NSString *text = [obj objectForKey:#"TestoMessaggio"];
height = 30 + [self getStringHeight:text andFont:[UIFont systemFontOfSize:13]] + 10;
}
return height;
}
- (void) setPullDownToRefresh {
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(aggiornaTabella:) forControlEvents:UIControlEventValueChanged];
[self.messagesTableView addSubview:refreshControl];
}
- (void) aggiornaTabella:(UIRefreshControl *)myRefreshControl {
self.arrayMessaggi = [NSMutableArray arrayWithArray:objects];
self.messagesTableView = [[UITableView alloc] init];
[self.messagesTableView reload data];
}

UITableViewCell shifts the content when reloaded

I am using a custom UITableViewCell with a UILabel at the top ,a UIButton just below the label and another UILabel,just under this button.
Final UILabel will be hidden initially,and will be opened when button action is called.The height of all the label and the cell are dynamic.
But
When i select the button ,the cell shifts its contentview to the.
center
I need the content of the cells to start at the origin itself.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"ReferenceCell";
ReferenceiPadTableCell *cell = (ReferenceiPadTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ReferenceiPadTableCell" owner:self options:Nil];
cell = [nib objectAtIndex:0];
cell.accessoryView = nil;
}
tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
NSDictionary *referenceDictionary = [self.referencesList objectAtIndex:indexPath.row];
NSString *nameString = [referenceDictionary objectForKey:#"name"];
CGSize labelSize = [nameString sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(listTableView.frame.size.width - 15, 125)
lineBreakMode:UILineBreakModeWordWrap];
labelSize.height = labelSize.height > 96? labelSize.height : 96;
cell.l1.text = nameString;
cell.l1.frame = CGRectMake(cell.l1.frame.origin.x, 6, cell.l1.frame.size.width, labelSize.height);
cell.button.tag = [[referenceDictionary objectForKey:#"sort"] intValue];
[cell.button addTarget:self action:#selector(showList:) forControlEvents:UIControlEventTouchUpInside];
cell.l2.hidden = YES;
cell.button.frame = CGRectMake(cell.button.frame.origin.x, cell.l1.frame.origin.y+ labelSize.height + 1, cell.l1.frame.size.width, cell.l1.frame.size.height);
if ([self.showList objectForKey:[NSString stringWithFormat:#"showList-%d", indexPath.row]] )
{
cell.l2.hidden = NO;
NSDictionary *dic = [self.abstractList objectAtIndex:indexPath.row];
NSString *abtString = [dic objectForKey:#"name"];
CGSize absSize = [abtString sizeWithFont:[UIFont systemFontOfSize:14]
constrainedToSize:CGSizeMake(tableView.frame.size.width - 15, 125)
lineBreakMode:UILineBreakModeWordWrap];
cell.l2.frame = CGRectMake(cell.button.frame.origin.x, cell.button.frame.origin.y+ cell.button.frame.size.height + 3, cell.button.frame.size.width, absSize.height);
cell.l2.text = abtString;
}
return cell;
}
it's doesn't shift the content but added more subview on UITableViewCell because you are not using reusing cell concept well.So use concept like this
-(UITableViewCell *)tableView:(UITableView *)tableView reuseTableViewCellWithIdentifier:(NSString *)identifier withIndexPath:(NSIndexPath *) indexPath
{
UITableViewCell *cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
UILabel *lbl=[[UILabel alloc]init];
lbl.lineBreakMode = NSLineBreakByWordWrapping;
lbl.numberOfLines = 0;
lbl.backgroundColor=[UIColor clearColor];
lbl.textAlignment=NSTextAlignmentCenter;
UIImageView *imgView=[[UIImageView alloc]init];
UIImageView *imgView1=[[UIImageView alloc]init];
UIImageView *imgView2=[[UIImageView alloc]init];
UIImageView *imgView3=[[UIImageView alloc]init];
UIImageView *imgView4=[[UIImageView alloc]init];
if(UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPhone)
{
lbl.font=[UIFont fontWithName:#"Marker Felt" size:20];
}
else
{
lbl.font=[UIFont fontWithName:#"Marker Felt" size:30];
}
[cell.contentView addSubview:lbl];
[cell.contentView addSubview:imgView];
[cell.contentView addSubview:imgView1];
[cell.contentView addSubview:imgView2];
[cell.contentView addSubview:imgView3];
[cell.contentView addSubview:imgView4];
return cell;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell=[self tableView:tableView reuseTableViewCellWithIdentifier:CellIdentifier withIndexPath:indexPath];
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
}
}
}

iOS - Displaying an array of objects inside of a single cell - repeatedly

I have not found any good resource on here so I thought it would be great to get this up and out there... and stop me from pulling my hair out.
Acting like the app "Agenda" (calendar app) - I have a tableview with each cell representing a day. The next step is to place the eventsArray inside the appropriate cell - through cellForRowAtIndexPath.
I am only familiar with displaying the eventsArray with sections and rows - using each indexPath to represent an event... not an array of events. (Below I posted working code for others looking for help in that department, and as a reference).
It would be great if someone could put up some code to execute the eventsArray inside a single cell - I'm assuming it is a use of the cellForRowAtIndexPath I am not familiar with. Thank you in advance. Any questions just shoot.
{
#pragma mark - TableView stuff
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
A1Section *a1section = [self.sections objectAtIndex:section];
return [a1section.rows count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.sections count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
A1Section *a1section = [self.sections objectAtIndex:section];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"EEEE, MMM d, yyyy"];
NSString *myDateString = [formatter stringFromDate:a1section.date];
return [NSString stringWithFormat:#"%#", myDateString];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 47;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UILabel *timeLabel = nil;
UILabel *nameLabel = nil;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor redColor];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(11.0, 13.0, 55.0, 15.0)];
[timeLabel setTag:1];
[timeLabel setBackgroundColor:[UIColor clearColor]];
timeLabel.textAlignment = UITextAlignmentLeft;
[timeLabel setFont:[UIFont fontWithName:#"HelveticaNeue-Bold" size:14]];
[timeLabel setTextColor:[UIColor blackColor]];
[timeLabel setLineBreakMode:NSLineBreakByClipping];
[timeLabel setNumberOfLines:1];
[cell.contentView addSubview:timeLabel];
nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(85.0, 11.0, 200.0, 20.0)]; //x = 80.0, width = 235
[nameLabel setTag:2];
[nameLabel setBackgroundColor:[UIColor clearColor]];
nameLabel.textAlignment = UITextAlignmentLeft;
[nameLabel setFont:[UIFont fontWithName:#"HelveticaNeue-Bold" size:17]];
[nameLabel setTextColor:[UIColor blackColor]];
[nameLabel setLineBreakMode:NSLineBreakByTruncatingTail];
[nameLabel setNumberOfLines:1];
[cell.contentView addSubview:nameLabel];
} else {
timeLabel = (UILabel *)[cell.contentView viewWithTag:1];
nameLabel = (UILabel *)[cell.contentView viewWithTag:2];
}
A1Section *a1section = [self.sections objectAtIndex:indexPath.section];
PFObject *object = [a1section.rows objectAtIndex:indexPath.row];
NSDate *someDate = [object objectForKey:#"startDate"];
NSString *time = [self.dateFormatter stringFromDate:someDate];
[(UILabel *)[cell.contentView viewWithTag:1] setText:time];
[(UILabel *)[cell.contentView viewWithTag:2] setText:[object objectForKey:#"textContent"]];
return cell;
}
}
I'm not entirely sure what you're asking, but I presume you're asking how to use an array's contents for display in cellForRowAtIndexPath. If so, you would just have an array property that contains the data you want. Then, in cellForRowAtIndexPath, you can do something like
NSString *name = [self.dataArray objectAtIndex:indexPath.row];
nameLabel.text = name;
Does that answer your question?

Data lose On UITableViewCell When UITableView Scrolling?

I am trying to implement UITableview based application. In my tableView their is 10 Section and each section having one row.
I want implement each section have Different type of ContentView(1-8 same ContentView 9th section Different ContentView). I did this code For that.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
UITextField *textField;
UITextView *textView;
NSUInteger section=[indexPath section];
if(section == 9){
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
textView=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, 290, 110)];
[textView setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor
]];
[textView setTag:([indexPath section]+100)];
[cell.contentView addSubview:textView];
}else{
textView=(UITextView*)[cell.contentView viewWithTag:([indexPath section]+100)];
}
return cell;
}else {
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if(cell==nil){
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
textField=[[UITextField alloc]initWithFrame:CGRectMake(5, 5, 290, 50)];
[textField setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
[textField setTag:([indexPath section]+100)];
[cell.contentView addSubview:textField];
}else{
textField=(UITextField*)[cell.contentView viewWithTag:([indexPath section]+100)];
}
return cell;
}
return nil;
}
My problem are:
1. After type some thing in the UITextField/UITextView i am scrolling in the UITableView. that time all data in the UITableViewCell(UITextField/UITextView) was lose, except last cell data.
2. If i create cell
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Instead of
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
Data will repeating . How can i over come this problem?
This line:
UITableViewCell *cell=[self.tableView cellForRowAtIndexPath:indexPath];
Should never appear in your data source cellForRowAtIndexPath method.
Apart from that, your code is OK, except that you are not setting the text field value anywhere. You need a model (such as an array of strings for the 10 textfield values). This model should be updated when the textfields are edited, and in your method above you copy the value back out of the model and into the textfield's text property:
textfield.text = [self.modelArray objectAtIndex:indexPath.section];
The table pools and reuses cells in an unpredictable fashion, so that subview of a cell that just scrolled off the bottom might reappear next at the top, or might be disposed of.
This is why you saw it partially work. The cell's subviews work okay until their cell gets reused or unloaded, then things move to the wrong place or data disappears.
The solution is that your table's datasource needs to hold onto it's own data. This is usually an array representing your model. Your case is a little unusual because you are using the text controls in your table as inputs, rather than display, which is more typical.
I suggest doing it like this:
// in #interface
#property (nonatomic, retain) NSMutableArray *sections;
// in #implementation
#synthesize sections=_sections;
// at some point before the view appears
self.sections = [NSMutableArray array];
for (int i=0; i<10; i++) {
UIControl *textControl;
if (i<9) {
textControl=[[UITextView alloc]initWithFrame:CGRectMake(5, 5, 290, 110)];
} else {
textControl=[[UITextField alloc]initWithFrame:CGRectMake(5, 5, 290, 50)];
}
[textControl setBackgroundColor:[UIColor scrollViewTexturedBackgroundColor]];
[textControl setTag:i+100];
[sections addObject:textControl];
[textControl release];
}
Now your cellForRowAtIndexPath is a little simpler:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier1 = #"Cell1";
static NSString *CellIdentifier2 = #"Cell2";
NSUInteger section=[indexPath section];
if(section == 9) {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
if(cell==nil) {
cell=[[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier1]autorelease];
}
} else {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
if(cell==nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier2]autorelease];
}
}
// who knows what subview this cell has? it might not have one, or it might have the wrong one
// just clean it up to be certain
for (UIView *view in cell.subviews) {
[view removeFromSuperView];
}
// get the textControl we set up for _this_ section/cell
UIControl *textControl = [self.sections objectAtIndex:section];
// now we have a fresh cell and the right textControl. drop it in
[cell addSubview:textControl];
return cell;
}
hey the reason is you are doing this things when cell is nil ? but you are not writing any code when cell is not nil.
look at this example , in this example i am adding image view in tableview cell , hence you can add textviews or any other views like this
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIImageView *imgView;
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
imgView = [[UIImageView alloc] initWithFrame:CGRectMake(100,0,100,62)];
[imgView setImage:[UIImage imageNamed:#"img.png"]];
imgView.tag = 55;
[cell.contentView addSubview:imgView];
[imgView release];
}
else
{
imgView = (id)[cell.contentView viewWithTag:55];
}
so as showin here imgView = (id)[cell.contentView viewWithTag:55]; you have to give tag to you and write code showing above in else..
Let you try to make the cell labels and textviews by using following code. It works for me.
if (tagvalue ==3) {
static NSString *CellIdentifier = #"Cell3";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
lbl7 = [[UILabel alloc] init];
[lbl7 setFont:[UIFont boldSystemFontOfSize:20]];
[cell.contentView addSubview:lbl7];
lbl7.backgroundColor = [UIColor clearColor];
lbl7.frame = CGRectMake(120, 5, 0, 40);
lbl7.tag = 70;
[lbl7 release];
lbl8 = [[UILabel alloc] init];
[lbl8 setFont:[UIFont boldSystemFontOfSize:18]];
[cell.contentView addSubview:lbl8];
lbl8.backgroundColor = [UIColor clearColor];
lbl8.textColor = [UIColor grayColor];
lbl8.frame = CGRectMake(120, 50, 0, 40);
lbl8.tag = 80;
[lbl8 release];
lbl7 = (UILabel*)[cell.contentView viewWithTag:70];
lbl8 = (UILabel*)[cell.contentView viewWithTag:80];
lbl7.text = [[rowsarray objectAtIndex:row]objectForKey:#"name"];
lbl8.text = [[rowsarray objectAtIndex:row]objectForKey:#"flavour"];
[lbl7 sizeToFit];
[lbl8 sizeToFit];
return cell;
}
if (tagvalue ==4) {
static NSString *CellIdentifier = #"Cell4";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
lbl9 = [[UILabel alloc] init];
[lbl9 setFont:[UIFont boldSystemFontOfSize:20]];
[cell.contentView addSubview:lbl9];
lbl9.backgroundColor = [UIColor clearColor];
lbl9.frame = CGRectMake(120, 5, 0, 40);
lbl9.tag = 90;
[lbl9 release];
lbl10 = [[UILabel alloc] init];
[lbl10 setFont:[UIFont boldSystemFontOfSize:18]];
[cell.contentView addSubview:lbl10];
lbl10.backgroundColor = [UIColor clearColor];
lbl10.textColor = [UIColor grayColor];
lbl10.frame = CGRectMake(120, 50, 0, 40);
lbl10.tag = 100;
[lbl10 release];
lbl9 = (UILabel*)[cell.contentView viewWithTag:90];
lbl10 = (UILabel*)[cell.contentView viewWithTag:100];
lbl9.text = [[rowsarray objectAtIndex:row]objectForKey:#"name"];
lbl10.text = [[rowsarray objectAtIndex:row]objectForKey:#"flavour"];
[lbl9 sizeToFit];
[lbl10 sizeToFit];
return cell;
}
I had same issue. Its not the problem with table class. The issue is at the place where you are calling this tableviewcontroller. First make the object of this call in .h and then allocate in .m, thats it..
When I was declaring in viewdidload like tbl *t = [self.storyboard...];, I was also facing the same problem. But when I put tbl *t; in .h problem solved.

problem with cellForRowAtIndexPath method in UITableView iphone (indexPath.row is null)

Table view cell management has driving me crazy from past two days. Please check the code below and I will explain you the problem in detail..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *nameLabel,*sugarLabel,*searchNameLabel,*searchSugarLabel;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
CGFloat width = [UIScreen mainScreen].bounds.size.width - 50;
CGFloat height = 20;
CGRect frame = CGRectMake(10.0f, 10.0f, width, height);
if(isSearchOn)
{
searchNameLabel = [[UILabel alloc] initWithFrame:frame];
searchNameLabel.textColor = [UIColor blackColor];
searchNameLabel.backgroundColor = [UIColor clearColor];
searchNameLabel.textAlignment = UITextAlignmentLeft;
searchNameLabel.font = [UIFont systemFontOfSize:14.0f];
searchNameLabel.tag=260;
[cell.contentView addSubview:searchNameLabel];
[searchNameLabel release];
searchSugarLabel= [[UILabel alloc] initWithFrame:frame];
searchSugarLabel.textColor = [UIColor blackColor];
searchSugarLabel.backgroundColor = [UIColor clearColor];
searchSugarLabel.textAlignment = UITextAlignmentLeft;
searchSugarLabel.font = [UIFont systemFontOfSize:14.0f];
searchSugarLabel.tag=160;
[searchSugarLabel setHidden:YES];
[cell.contentView addSubview:searchSugarLabel];
[searchSugarLabel release];
}
else{
nameLabel = [[UILabel alloc] initWithFrame:frame];
nameLabel.textColor = [UIColor blackColor];
nameLabel.backgroundColor = [UIColor clearColor];
nameLabel.textAlignment = UITextAlignmentLeft;
nameLabel.font = [UIFont systemFontOfSize:14.0f];
nameLabel.tag=60;
[cell.contentView addSubview:nameLabel];
[nameLabel release];
sugarLabel= [[UILabel alloc] initWithFrame:frame];
sugarLabel.textColor = [UIColor blackColor];
sugarLabel.backgroundColor = [UIColor clearColor];
sugarLabel.textAlignment = UITextAlignmentLeft;
sugarLabel.font = [UIFont systemFontOfSize:14.0f];
sugarLabel.tag=160;
[sugarLabel setHidden:YES];
[cell.contentView addSubview:sugarLabel];
[sugarLabel release];
}
}
else {
if(isSearchOn)
{
searchNameLabel=(UILabel *)[cell.contentView viewWithTag:260];
searchSugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
else{
nameLabel=(UILabel *)[cell.contentView viewWithTag:60];
sugarLabel=(UILabel *)[cell.contentView viewWithTag:160];
}
}
if (isSearchOn) {
cellValue = [searchResult objectAtIndex:indexPath.row];
searchSugarLabel.text=cellValue.sugarId;
NSString *searchText = [NSString stringWithFormat:#"%# %#", cellValue.firstName, cellValue.lastName];
searchNameLabel.text=searchText;
NSLog(#"%#",searchNameLabel.text);
NSLog(#"%#",searchSugarLabel.text);
}
else {
NSString *contact=[contactKeys objectAtIndex:[indexPath section]];
NSArray *contactSection=[contactNames objectForKey:contact];
sugar=[db getSugarId:#"Contacts" bySection:contact andIndex:indexPath.row];
NSString *cellText = [contactSection objectAtIndex:[indexPath row]];
// split the text by the : to get an array containing { "AAA", "BBB" }
NSArray *splitText = [cellText componentsSeparatedByString:#":"];
// form a new string of the form "BBB AAA" by using the individual entries in the array
NSString *contactText = [NSString stringWithFormat:#"%# %#", [splitText objectAtIndex:1], [splitText objectAtIndex:0]];
nameLabel.text = contactText;
sugarLabel.text = sugar;
}
return cell;
}
Contacts is a class which has the properties firstName,lastName and sugar id in it..I am assigning the properties of a contacts class to the variables in the database method and returning an array of contact objects. searchResult is now an array of contact objects.The problem is when I logged the contents on the console the database gets everything in it and returns an array of contacts.The contacts in the searchResult points to different memory locations but when I try to debug the cellForRowAtIndexPath method after it gets 6 contacts..the 7th contact points to the same memory location as the 1st and it repeats thus in the searchNameLabel.text it returns a null and indexPath points to nil...I think it is cell re use issue and I accept that I am very bad in that..I need to figure this out as I am going to finish off my project with this...please guys help me...
This happens only when I try to search for the contacts. It works fine when I try to load all the contacts onto the table..
You are initializing your subviews in the if(cell== nil) block, but in the corresponding else-block, you overwrite them again.
You should rethink your design: Do not load different views by searchon, but set their properties depending on searchon
if(cell == nil){
//do all initializing
}
if(searchon){
//set view/label properties for searching style
} else {
//set view/label properties for not-searching style
}
another approach could be to have totally separated NIB files for the searchon/!searchon
if(searchon){
static NSString *SearchOnCellIdentifier = #"SearchOnCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOnCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
} else {
static NSString *SearchOFFCellIdentifier = #"SearchOFFCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: SearchOFFCellIdentifier];
if (cell == nil){
//load cell from extra nib
}
}
NOTE: I never did that and it is not tested.