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!
Related
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.
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];
}
I need to add a UIButton in my UITableView only with my first and last array count. I found that we can use tableFooterView, to add unbutton below our tableview. But how can I achieve this over my tableview and only with first and last array values? Here 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];
}
//Adding a UIButton in last row
NSInteger lastSectionIndex = [editTable numberOfSections] - 1;
NSLog(#"lastSectionIndex:%d",lastSectionIndex);
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [editTable numberOfRowsInSection:lastSectionIndex] - 1;
NSLog(#"lastRowIndex:%d",lastRowIndex);
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
NSLog(#"last index:%#",pathToLastRow);
if (pathToLastRow.row == lastRowIndex)
{
NSLog(#"row enters");
checkButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
[checkButton1 setFrame:CGRectMake(200, 0, 168, 168)];
[checkButton1 addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[checkButton1 setBackgroundImage:[[UIImage imageNamed:#"Up Arrow.jpg"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
editTable.tableFooterView = checkButton1;
[cell addSubview:checkButton1];
}
Now I receive the buttons in every cell of my tableview. How can I give the button only to my first and last row array values? Thanks in advance.
Change your if condition as,
if ((lastSectionIndex == indexPath.section && lastRowIndex == indexPath.row ) || (indexPath.section == 0 && indexPath.row == 0 ))
{
It will look like this,
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIButton *checkButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
checkButton1.tag = 100;//not recommended, I would suggest to use custom UITableViewCell class and add this button as subview inside its init method
[checkButton1 setFrame:CGRectMake(200, 0, 168, 168)];
[checkButton1 addTarget:self
action:#selector(customActionPressed:)
forControlEvents:UIControlEventTouchDown];
[checkButton1 setBackgroundImage:[[UIImage imageNamed:#"Up Arrow.jpg"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0] forState:UIControlStateNormal];
[cell addSubview:checkButton1];
}
//Adding a UIButton in last row
NSInteger lastSectionIndex = [editTable numberOfSections] - 1;
NSLog(#"lastSectionIndex:%d",lastSectionIndex);
// Then grab the number of rows in the last section
NSInteger lastRowIndex = [editTable numberOfRowsInSection:lastSectionIndex] - 1;
NSLog(#"lastRowIndex:%d",lastRowIndex);
// Now just construct the index path
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
NSLog(#"last index:%#",pathToLastRow);
UIButton *checkButton1 = (UIButton *)[cell viewWithTag:100];//not recommended, I would suggest to use custom UITableViewCell class and add this button as subview inside its init method
if ((lastSectionIndex == indexPath.section && lastRowIndex == indexPath.row ) || (indexPath.section == 0 && indexPath.row == 0 ))
{
checkButton1.hidden = NO;
} else {
checkButton1.hidden = YES;
}
You dont have to declare checkButton1 in .h file. Make it a local variable as shown above. Then you can set hidden property to hide/show in difference cells. Instead of doing the above, you can also create this button in custom UITableViewCell class and set the hidden property as cell.checkButton1.hidden = YES. You need to subclass UITableViewCell for that.
instead of creating Button in CellforRow You can Create in ViewDidload And attach it with FooterView of table.
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[aButton setTitleColor:[UIColor colorWithWhite:0.0 alpha:0.56] forState:UIControlStateDisabled];
[aButton setBackgroundImage:[[UIImage imageNamed:#"test.png"] stretchableImageWithLeftCapWidth:kButtonSliceWidth topCapHeight:0] forState:UIControlStateNormal];
[aButton setTitle:#"Click me" forState:UIControlStateNormal];
[aButton.titleLabel setFont:[UIFont boldSystemFontOfSize:kFontSize14]];
[aButton setFrame:CGRectMake(10.0, 15.0, 300.0, 44.0)];
[self.tableView setTableFooterView:aButton];
Same thing you can do for headerview. or else You Can Use Viewforheader method
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0, 320, 44)] autorelease]; // x,y,width,height
UIButton *reportButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
reportButton.frame = CGRectMake(80.0, 0, 160.0, 40.0); // x,y,width,height
[reportButton setTitle:#"rep" forState:UIControlStateNormal];
[reportButton addTarget:self
action:#selector(buttonPressed:)
forControlEvents:UIControlEventTouchDown];
[headerView addSubview:reportButton];
return headerView;
}
You should add first button to your table view Header And other button should be added to your footer view Secion of tableView
I have a UITableViewCell. I can add and subtract 1 from the cell's textLabel and I can also delete the cells. Here is my problem, Lets say i add 5 to the value of the textLabel. And this cell is at the 0 indexPath (The First cell in the table). When I delete this cell and there are now no longer any cells on the table, I add a new cell and this new cell automatically gets the same value as the cell that was just deleted. SO this new cell will have a value of 5 and i want the cell to have a value of 1 just like every cell should when it is added. This only happens when a cell is deleted and a new cell is added at that exact same indexPath. So my question is: do i have to delete this cells "memory" or "data" for this to be fixed? Thanks a bunch for the help!
CellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
addBtn = [[UIButton alloc]init];
addBtn =[UIButton buttonWithType:UIButtonTypeRoundedRect];
[addBtn setFrame:CGRectMake(220,10,25,55)];
[addBtn addTarget:self action:#selector(addLabelText:) forControlEvents:UIControlEventTouchUpInside];
[addBtn setTitle:#"+" forState:UIControlStateNormal];
[addBtn setEnabled:YES];
[cell addSubview:addBtn];
subBtn = [[UIButton alloc]init];
subBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
[subBtn setFrame:CGRectMake(260,10,25,55)];
[subBtn addTarget:self action:#selector(subtractLabelText:) forControlEvents:UIControlEventTouchUpInside];
[subBtn setTitle:#"-" forState:UIControlStateNormal];
[subBtn setEnabled:YES];
[cell addSubview:subBtn];
//cell.textLabel.text = #"1";
}
//cellText.hidden=!self.editing;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
cell.textLabel.text = [number objectAtIndex:indexPath.row];
return cell;
}
When cells are deleted or go off screen, the table view saves them and reuses them later. So you need to reset textLabel's value in tableView:cellForRowAtIndexPath:. The UITableViewCell class reference says this:
The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell.
I have made a table and contents some values, I have a button coding like
cell.textLabel.textColor = [UIColor whiteColor];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setBackgroundImage:[UIImage imageNamed:#"edit_button.png"] forState:UIControlStateNormal];
[btn setFrame:CGRectMake(290, 15, 15, 15)];
[btn addTarget:self action:#selector(editTable:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
NSString *cellValue = [myArrayNew objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
I want to click that button and take values from that particular index,
like
Ali (button here) --------index 0
Sajid (button here) --------index 1
Robert (button here) --------index 2
RaM (button here) --------index 3
Theser are cells of table, now how can I get index as I click that button?
if you are not getting my question, you can ask me again...
I found my answer,
Just write the following coding inside the button targeted method and use clickButtonPath as your index path.
It is working perfectly, simply
UITableViewCell *clickedCell = (UITableViewCell *)[[sender superview] superview];
NSIndexPath *clickedButtonPath = [self.tableView indexPathForCell:clickedCell];
btn.tag = indexPath.row;
Then in (void)editTable:(id)sender:
int row = (UIButton *)btn.tag;
you would use something like this.
- (IBAction)editTable:(UIButton *)sender {
UIView *contentView = [sender superView];
UITableViewCell *cell = [contentView superView];
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
}
But first you should make sure to properly reuse your cells. By changing your code like this:
cell = ... dequeue cell ...
if (cell == nil) {
cell = ... create new cell ...
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.tag = 194;
[btn setBackgroundColor:[UIColor clearColor]];
[btn setBackgroundImage:[UIImage imageNamed:#"edit_button.png"] forState:UIControlStateNormal];
[btn setFrame:CGRectMake(290, 15, 15, 15)];
[btn addTarget:self action:#selector(editTable:)
forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:btn];
}
// if you need to change something for this button you can get it like this:
//UIButton *btn= [cell.contentView viewWithTag:194];
NSString *cellValue = [myArrayNew objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;