table cell drawing on same position - iphone

I have to populate numbers of row. when i uses
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
this line, after scrolling to some rows it redrawing rows on same position.see below screen
if i make cell nil i.e.
UITableViewCell *cell = nil;
then works fine,but it takes unexpecedly more memory. now my question is why its happening.
what is the relation of making cell nil to redrawing on same position?
This is my code:
- (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];
}
UIButton *questionButton=[UIButton buttonWithType:UIButtonTypeCustom];
questionButton.backgroundColor=[UIColor clearColor];
questionButton.tag=indexPath.row+1;
[questionButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
UIImageView *statusImageView=[[UIImageView alloc]initWithFrame:CGRectMake(190,25,23,23)];
NSString *statusImageName=[[NSString alloc]init];
statusImageName=#"Right";
[statusImageView setImage:[UIImage imageNamed:statusImageName]];
[questionButton addSubview:statusImageView];
if(indexPath.row%2==0)
{
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarLeft"] forState:UIControlStateNormal];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarLetSelected"] forState:UIControlStateHighlighted];
CGRect topicButtonFrame=CGRectMake(0, 10, 250, 70);
questionButton.frame=topicButtonFrame;
NSLog(#"Even Rows =%d",indexPath.row);
NSString *questionLabel=[NSString stringWithFormat:#" Question %d :",indexPath.row+1];
[questionButton setTitle:questionLabel forState:UIControlStateNormal];
//questionButton.titleLabel.textAlignment=NSTextAlignmentLeft;
[questionButton.titleLabel setTextAlignment:UITextAlignmentLeft];
}
else
{
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarRight"] forState:UIControlStateNormal];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarRightSelected"] forState:UIControlStateHighlighted];
CGRect topicButtonFrame=CGRectMake(100, 10, 250, 70);
questionButton.frame=topicButtonFrame;
NSString *questionLabel=[NSString stringWithFormat:#" Question %d :",indexPath.row+1];
[questionButton setTitle:questionLabel forState:UIControlStateNormal];
questionButton.titleLabel.textAlignment=UITextAlignmentRight;
[cell addSubview:questionButton];
}
[cell addSubview:questionButton];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
return cell;
}

The purpose of dequeueReusableCellWithIdentifier is to use less memory. If the screen can fit 4 or 5 table cells, then with reuse you only need to have 4 or 5 table cells allocated in memory even if the table has 1000 entries.
So when you do this UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; and it returns an old cell to reuse. It is not a new cell instance. It contains UI elements of the cell initialised to the old data. To display it again you need to reset all the UI elements and put in your new values.
The second way when you put UITableViewCell *cell = nil; there is no reuse. There is no advantage in the second way over just using an array of table cells. If your table has 1000 entries then you will have 1000 cells allocated in memory. If you are going to do that you would put them in an array and just index the array with the row number and return the cell. This should explain your spike in memory usage as it is not reusing any cell instance.
For small tables with fixed cells second solution may be an reasonable solution, for dynamic or large tables reusing is the best way to go...
UPDATE: since you have asked for some code. Also note that you are doing 2 types of rending depending on odd or even. So the cell that comes out of reuse might be odd when you want to show even numbered question. In that case you would need to reset the cell just after the cell is got (either from reuse or created new) and let your normal logic flow through...
[questionButton setBackgroundImage:[UIImage imageNamed:#"default.png"]];
[questionButton setTitle:#"" forState:UIControlStateNormal];
CGRect topicButtonFrame=CGRectMake(0, 0, 250, 70);
questionButton.frame=topicButtonFrame;

The problem is here :
[cell addSubview:questionButton];
}
[cell addSubview:questionButton];
You are adding the questionButton twice. Please remove one in else section and try.
Update :
Can you try this just for the confirmation what is the problem:
if(indexPath.row%2==0)
{
UIButton *questionButton=[UIButton buttonWithType:UIButtonTypeCustom];
questionButton.backgroundColor=[UIColor clearColor];
questionButton.tag=indexPath.row+1;
[questionButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
UIImageView *statusImageView=[[UIImageView alloc]initWithFrame:CGRectMake(190,25,23,23)];
NSString *statusImageName=[[NSString alloc]init];
statusImageName=#"Right";
[statusImageView setImage:[UIImage imageNamed:statusImageName]];
[questionButton addSubview:statusImageView];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarLeft"] forState:UIControlStateNormal];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarLetSelected"] forState:UIControlStateHighlighted];
CGRect topicButtonFrame=CGRectMake(0, 10, 250, 70);
questionButton.frame=topicButtonFrame;
NSString *questionLabel=[NSString stringWithFormat:#" Question %d :",indexPath.row+1];
[questionButton setTitle:questionLabel forState:UIControlStateNormal];
//questionButton.titleLabel.textAlignment=NSTextAlignmentLeft;
[questionButton.titleLabel setTextAlignment:UITextAlignmentLeft];
[cell addSubview:questionButton];
}
else
{
UIButton *questionButton=[UIButton buttonWithType:UIButtonTypeCustom];
questionButton.backgroundColor=[UIColor clearColor];
questionButton.tag=indexPath.row+1;
[questionButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
UIImageView *statusImageView=[[UIImageView alloc]initWithFrame:CGRectMake(190,25,23,23)];
NSString *statusImageName=[[NSString alloc]init];
statusImageName=#"Right";
[statusImageView setImage:[UIImage imageNamed:statusImageName]];
[questionButton addSubview:statusImageView];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarRight"] forState:UIControlStateNormal];
[questionButton setBackgroundImage:[UIImage imageNamed:#"TopicsbarRightSelected"] forState:UIControlStateHighlighted];
CGRect topicButtonFrame=CGRectMake(100, 10, 250, 70);
questionButton.frame=topicButtonFrame;
NSString *questionLabel=[NSString stringWithFormat:#" Question %d :",indexPath.row+1];
[questionButton setTitle:questionLabel forState:UIControlStateNormal];
questionButton.titleLabel.textAlignment=UITextAlignmentRight;
[cell addSubview:questionButton];
}

Related

Display button click count in label for particular cell which are subviews to uitableview

I have a button and a label which are sub views to UITableView.
Initially label value is 0.
what i need is, when i click button on particular cell i want to increment value in same cell label (as 1) and display that value in same label.
And again i clicked same cell button the label in that cell should be increment (as 2) and display that value in same cell in UITableView.
My code..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *Lbl;
UIButton *btn;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
Lbl =[[UILabel alloc]init];
[Lbl setFrame:CGRectMake(56, 60, 117, 12)];
[Lbl setBackgroundColor:[UIColor clearColor]];
[Lbl setTextAlignment:NSTextAlignmentLeft];
[Lbl setFont:[UIFont boldSystemFontOfSize:15.0]];
Lbl.tag=indexPath.row;
[cell.contentView addSubview:Lbl];
btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"add" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateHighlighted];
[[btn titleLabel] setFont:[UIFont boldSystemFontOfSize:23]];
[btn setFrame:CGRectMake(289, 2, 30, 71)];
btn.tintColor=[UIColor lightGrayColor];
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(increaseItemCount:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
} else {
Lbl =(UILabel *)[cell.contentView viewWithTag:indexPath.row];
btn =(UIButton *)[cell.contentView viewWithTag:indexPath.row];
}
cell.textLabel.text=#"title";
countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
return cell;
}
// button action method
-(void)increaseItemCount:(UIButton *)sender
{
UITableViewCell *cell = (UITableViewCell *)sender.superview.superview;
NSIndexPath *path = [tableView indexPathForCell:cell];
NSLog(#"row: %d",path.row);
UILabel *countLbl =(UILabel *)[cell.contentView viewWithTag:path.row];
showItemCount=[countLbl.text intValue] + 1;
NSLog(#"%d",showItemCount);
countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
}
I tried this, After clicking the value is showing in other cells and when i scroll the table view that value is showing in all cells.
Any suggestions or code
If you want source code, Download it from here https://github.com/MasudShuvo/TestCustomTableViewCell
I've modify the code as your requirement.
That's because it looks like you're using a single instance variable to store the itemCount. You should use an array to know which cell has been clicked how many times.
The code is however pretty messy, so you should write it again from scratch
indexPath.row begins 0 to n, we not set tag 0 for label and you use single variable showItemCount used to assign text in countLbl, table view reuse cell when it will appear,use array to store showItemCount for each cells
please do as per following:
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
selectedIndex=-1;
//[tblView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 2;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// UILabel *Lbl;
// UIButton *btn;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UILabel *Lbl =[[UILabel alloc]init];
[Lbl setFrame:CGRectMake(56, 60, 117, 12)];
[Lbl setBackgroundColor:[UIColor clearColor]];
[Lbl setTextAlignment:NSTextAlignmentLeft];
[Lbl setFont:[UIFont boldSystemFontOfSize:15.0]];
Lbl.tag=indexPath.row;
Lbl.text=[NSString stringWithFormat:#"%i",0];
[cell.contentView addSubview:Lbl];
UIButton *btn =[UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:#"add" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateNormal];
[btn setTitleColor:[UIColor colorWithRed:0.7 green:0 blue:0 alpha:1.0] forState:UIControlStateHighlighted];
[[btn titleLabel] setFont:[UIFont boldSystemFontOfSize:23]];
[btn setFrame:CGRectMake(289, 2, 30, 71)];
btn.tintColor=[UIColor lightGrayColor];
btn.tag=indexPath.row;
[btn addTarget:self action:#selector(increaseItemCount:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
NSLog(#"Selected Index:%i",indexPath.row);
} else {
UILabel *Lbl =(UILabel *)[cell.contentView viewWithTag:indexPath.row];
//UIButton *btn =(UIButton *)[cell viewWithTag:indexPath.row];
if(indexPath.row==selectedIndex)
{
NSLog(#"Selected Index in CellForRowAtIndexPath:%i",indexPath.row);
Lbl.text=[NSString stringWithFormat:#"%i",[Lbl.text intValue]+1];
}
}
// cell.textLabel.text=#"title";
//countLbl.text = [[NSString alloc] initWithFormat:#"%d",showItemCount];
return cell;
}
-(void)increaseItemCount:(UIButton *)sender
{
selectedIndex=sender.tag;
[tblView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected Index:%i",indexPath.row);
}
i hope this will help you.

UITableView cell reuse, low Memory Warning, App Crashing in device after loading images

Please help me writing good code
My Scenario:
loading image in tableview from custom image array(size can be 1-1000 or may be more)- Done
Placed Image on Button-Done (Dont know right way but working fine)
Getting Image tag with the help of button-Done
Not to load extra images in cell (suppose 4 image view in one cell and 26 images)-Done
I am Loading Images in UItableView but app only crashing in device, working fine in simulator. i have googled and found some answer on reusing cell modified my code accordingly to some extent. But i am still not sure about that image loading and crashing. Some time when the image are less it crash on scrolling and some time just after loading images in table view.
I am close to my solution but not getting good result. Please Help!!
Please check my code and modify it if required
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *CellIdentifier =[NSString stringWithFormat:#"%i-%i", indexPath.section,indexPath.row];
// static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell;
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
NSInteger imageIndex = [indexPath row] * 4;
NSInteger size = [imageArray count];
imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 80,80)];
imageView1.image = [imageArray objectAtIndex:imageIndex];
aButton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton1 setTag:imageIndex];
[aButton1 setImage:imageView1.image forState:UIControlStateNormal];
aButton1.frame = CGRectMake(0, 0, 80,80);
[aButton1 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton1];
if (size == imageIndex +1) {
return cell;
}
imageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(80, 0, 80,80)];
// imageView2.tag= tagValue+2000;
imageView2.image = [imageArray objectAtIndex:imageIndex+1];
[cell.contentView addSubview:imageView2];
UIButton* aButton2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton2 setTag:imageIndex+1];
[aButton2 setImage:imageView2.image forState:UIControlStateNormal];
aButton2.frame = CGRectMake(80, 0, 80,80);
[aButton2 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton2];
if (size == imageIndex + 2) {
return cell;
}
imageView3 = [[UIImageView alloc] initWithFrame:CGRectMake(160, 0, 80,80)];
imageView3.image = [imageArray objectAtIndex:imageIndex+2];
UIButton* aButton3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton3 setTag:imageIndex+2];
[aButton3 setImage:imageView3.image forState:UIControlStateNormal];
aButton3.frame = CGRectMake(160, 0, 80,80);
[aButton3 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton3];
if (size == imageIndex + 3) {
return cell;
}
imageView4 = [[UIImageView alloc] initWithFrame:CGRectMake(240, 0, 80,80)];
imageView4.image = [imageArray objectAtIndex:imageIndex+3];
UIButton* aButton4 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton4 setTag:imageIndex+3];
[aButton4 setImage:imageView4.image forState:UIControlStateNormal];
aButton4.frame = CGRectMake(240, 0, 80,80);
[aButton4 addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton4];
}
else
{
NSLog(#"old one");
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
return cell;
}
The problem is with this line
NSString *CellIdentifier =[NSString stringWithFormat:#"%i-%i", indexPath.section,indexPath.row];
Each of the row is created and none of the cells are reused except when scrolling back to already displayed cells.
A better way would be to take advantage of reuse of cells by using a identifier to give a cell back when it goes out of view and then styling it according to the requirement. More like NSString *CellIdentifier =#"MyCellIdentifier";
Now check the section and row for the cell and style it accordingly.
I think size of the image matters. Can you try loading with image of very small size say less than 5kb and see (just for testing purpose) ?

Stop reloading of table data in UITableView when it pulls/scrolls

I know it is not general practice to do this but my application need this functionality. I am very new to iPhone programming. When the user pulls/scrolls the table screen it gets updated I have to stop it. Also order of the data get changed when I pull it.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
[button addTarget:self action:#selector(optionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:optionValue forState:UIControlStateNormal];
[button setTag:indexPath.row];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.contentView addSubview:button];
[button release];
}
return cell;
}
First, the way you are using cellForRowAtIndexPath is wrong.
static NSString *MyIdentifier = #"MyIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 300, 50)];
[button addTarget:self action:#selector(optionButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[cell.contentView addSubview:button];
[button release];
}
//These should be outside of the cell == nil loop so that they get refreshed correctly
[button setTitle:optionValue forState:UIControlStateNormal];
[button setTag:indexPath.row];
return cell;
Secondly, I don't see where you set optionValue, but if you don't want to hit the database every time, then store the values in an NSArray and get the values from the array. This way you only hit the database once when you load the view.

add label on cell in table view and access it on buttonClicked Method.....:)

i am a new Programmer.... i wants add two labels on cell in table view.....and access the label.text in buttonClicked method.....
i am new programmer..so i don't know add label on table cell.... is I am right?
thanks in advance...for giving your valuable time for my code....:)
///insert individual row into the table view
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[NSString stringWithFormat:#"Cell %i",indexPath.section]];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:[NSString stringWithFormat:#"Cell %i",indexPath.section]] autorelease];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;//my code.... change the color or selected cell
search_items *pro = [searchCount objectAtIndex:[indexPath row]];
/// i wants access these two labels on buttonClicked Method...
UILabel *showroomName = [[UILabel alloc] initWithFrame:anySize];
[showroomName setText:pro.s_showroomName];
[cell addSubview:showroomName];
[showroomName release];
UILabel *productName = [[UILabel alloc] initWithFrame:anySize];
[productName setText:pro.s_productName];
[cell addSubview:productName];
[productName release];
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
aButton.frame = CGRectMake(150, 15,150,40);
[aButton setTag:indexPath.row];
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:aButton];
UIImage *img = [UIImage imageNamed:#"image.png"];
[aButton setImage:img forState:UIControlStateNormal];
[aButton setTitle:#"View Details" forState:UIControlStateNormal];
[aButton addSubview:buttonLabel1];
NSString *filepath=[[NSBundle mainBundle]pathForResource:pro.s_image ofType:#"png"];
UIImage *image=[UIImage imageWithContentsOfFile:filepath];
cell.imageView.image=image;
return cell;
}
-(void)buttonClicked:(UIButton*)sender {
//int tag = sender.tag;
}
UILabel *showroomName = [[UILabel alloc] initWithFrame:anySize];
[showroomName setText:pro.s_showroomName];
cell.accessoryView = showroomName;
Try this for memory management: Alloc the label in a method that gets called a single time (like viewDidLoad, viewWillAppear, viewDidAppear, init, even numberOfSectionInTableView) and just change it's text or whatever you want to change in cellForRowAtIndexPath. This way, you will not have leaks, bad memory management or useless memory allocated. And also, be very careful with realeasing. You should release the objects when you are sure that you won't need those. Some objects might still need them after you release them.

UITableViewCell and images overlapping

i have a strange issue with my UITableView...I add a UIButton as a subview to each cell , but when any of the cells gets out of view something happens, and when i scroll up again , i can see that the UIButton background images of some cells are overlapping !
The cellForRowAtIndexPath method i use contains the following code , which adds the UIButton instances
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyCell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:#"MyCell"];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
UIFont *titleFont = [UIFont fontWithName:#"Arial-BoldMT" size:14.0];
[[cell textLabel] setFont:titleFont];
[cell autorelease];
}
if([cell viewWithTag:indexPath.row]==nil){
UIButton *buttonLeft = [UIButton buttonWithType:UIButtonTypeCustom];
buttonLeft.tag=indexPath.row;
if ([[myArray objectAtIndex:indexPath.row] isEqualToString:#"item1"]) {
[buttonLeft addTarget:self action:#selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:#"item1.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];
}else{
[buttonLeft addTarget:self action:#selector(doThat:) forControlEvents:UIControlEventTouchUpInside];
[buttonLeft setBackgroundImage:[UIImage imageNamed:#"item2.png"] forState:UIControlStateNormal];
[buttonLeft setFrame: CGRectMake( 5.0f, 6.2f, 30.0f, 30.0f)];
}
[cell addSubview:buttonLeft];
}
cell.textLabel.text=[NSString stringWithFormat:#" %#",[myArray objectAtIndex:indexPath.row]];
return cell;
}
Apparently , this code for some reason adds the UIButton everytime the cell is displayed. I want each button subview to be added only once..
What am i doing wrong ?
Your help is much appreciated
That is because the table view reuses cells for performance reasons. Therefore, the cellForRowAtIndexPath: method, correctly implemented like yours, returns cells that already exist and only creates a new one if there is no reusable cell available.
Put all your button-related code within if (cell == nil) {}, so that the button is only added to "fresh" cells and it should work!