I have a UITableView with 20 rows. In each row, two UIButtons are added, so totally I have 40 buttons. How can I access each button in each cell? All those UIButton have the two tags 1 and 2.
For example: I want to write a method to change the background color of 2 buttons in a particular row:
-(void)changeColor:(int)row{
//code here
}
Do you have any suggestion?
-(UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Cell"] autorelease];
UIButton *button1=[[UIButton alloc] initWithFrame:CGRectMake(x1,y1,w1,h1)];
UIButton *button2=[[UIButton alloc] initWithFrame:CGRectMake(x2,y2,w2,h2)];
[button1 setTag:1];
[button2 setTag:2];
[[cell contentView] addSubview:button0 ];
[[cell contentView] addSubview:button1 ];
[button0 release];
[button1 release];
}
UIButton *button1 = (UIButton *)[cell viewWithTag:1];
UIButton *button2 = (UIButton *)[cell viewWithTag:2];
return cell;
}
You should be able to do this:
-changeColor:(int)row
{
NSIndexPath indexPath = [NSIndexPath indexPathForRow:row inSection:0]; // Assuming one section
UITableViewCell *cell = [myTableView cellForRowAtIndexPath:indexPath];
UIButton *button1 = (UIButton *)[[cell contentView] viewWithTag:1];
UIButton *button2 = (UIButton *)[[cell contentView] viewWithTag:2];
}
*some syntax might be wrong. I dont have Xcode handy
If you want to change the button color to have a highlighted / downstate I suggest to use the following:
[yourButton addTarget:self action:#selector(goToView:) forControlEvents:UIControlEventTouchUpInside];
[yourButton addTarget:self action:#selector(changeColor:) forControlEvents:UIControlEventTouchDown];
[yourButton addTarget:self action:#selector(touchCancel:) forControlEvents:UIControlEventTouchDragExit];
-(void)buttonAction:(UIButton*)sender
{
[self touchCancel:sender];
/* DO SOME MORE ACTIONS */
}
-(void)changeColor:(UIButton*)sender
{
sender.backgroundColor = [UIColor redColor];
}
-(void)touchCancel:(UIButton*)sender
{
sender.backgroundColor = [UIColor clearColor];
}
If you want to make the button have a different selected color, create an array that holds all the selected states. Then use the array to check if the button color needs a different color in cellForRowAtIndexPath.
When you want to change the button color just change the value in the array and call
[self.tableView reloadData];
Be sure to do it outside the if (cell == nil) method so it is also called when the cell is reused.
Related
I created the UITableView programatically, and in my UITableView have 3 rows in the UITableView section. I have a UIButton in 3 rows. Initially, all the buttons of three rows have gray color. If I select the button in the 2nd row, then the button in the 2nd row should be red and the all others gray and so on. Can any one suggest me.
In your cellForRowAtIndexPath
UIButton *button = [[UIButton alloc]initWithFrame:Your Frame];
[button addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
button.tag = indexPath.section;
[cell.contentView addSubview:button];
Then write buttonClicked method
-(void)buttonClicked:(UIButton*)button
{
UIButton *but1;
UIButton *but2;
if (button.tag == 0)
{
but1 = (UIButton *)[self.view viewWithTag:1];
but2 = (UIButton *)[self.view viewWithTag:2];
[but1 setBackgroundColor:[UIColor grayColor]];
[but2 setBackgroundColor:[UIColor grayColor]];
[button setBackgroundColor:[UIColor redColor]];
}
if (button.tag == 1)
{
but1 = (UIButton *)[self.view viewWithTag:0];
but2 = (UIButton *)[self.view viewWithTag:2];
[but1 setBackgroundColor:[UIColor grayColor]];
[but2 setBackgroundColor:[UIColor grayColor]];
[button setBackgroundColor:[UIColor redColor]];
}
if (button.tag == 2)
{
but1 = (UIButton *)[self.view viewWithTag:0];
but2 = (UIButton *)[self.view viewWithTag:1];
[but1 setBackgroundColor:[UIColor grayColor]];
[but2 setBackgroundColor:[UIColor grayColor]];
[button setBackgroundColor:[UIColor redColor]];
}
}
Hope it helps.
Try this:
Create the button as mentioned by patil (look below for his answer) ,and try to give it a tag.
button.tag=indexpath.section;
You need to set target-action of each button.Write the following line in the button action method:
[button setTarget:self action:#selector(someMethod:) forControlEvents:UIControlEventTouchUpInside];
Then implement someMethod: like this:
- (void)someMethod:(UIButton *)sender {
if (sender.tag == 1) {
// do action for button with tag 1
//change color here
[button setBackgroundColor:[UIColor redColor]];
} else if (sender.tag == 2) {
// do action for button with tag 2
} // ... and so on
}
I'm not too fond of the multiple if cases as you would need to re-write a lot when your amount of sections / rows change.
This is a more generic answer but it might not be so easy as the others. It involves created a UIButton subclass and a UITableViewCell subclass.
Create a UIButton subclass with a property to store the NSIndexPath of the cell where the button will be shown on:
//
// IndexPathButton.h
//
//
// Created by You on 28/07/15.
//
//
#import <UIKit/UIKit.h>
#interface IndexPathButton : UIButton
#property (nonatomic) NSIndexPath *indexPath;
#end
There should not be anything implemented in the .m file.
Create a UITableViewCell subclass which has the custom IndexPathButton on it. If you need help creating a custom UITableViewCell I suggest searching on SO or creating a new question.
In your UIViewController with your UITableView do the import of the custom UIButton
#import "IndexPathButton.h"
Also create an class variable to store the selectedIndexPath:
NSIndexPath *selectedButtonIndexPath;
Now we can start changing the UITableViewDataSource method:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"SomeCell";
YourCustomCellWithButton *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell)
{
cell = [[YourCustomCellWithButton alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
}
//Default setup of IndexPathButton on YourCustomCellWithButton
cell.button.backgroundColor = [UIColor grayColor];
cell.button.indexPath = indexPath; //Here we store the indexPath for later use
[cell.button addTarget:self action:#selector(cellButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
//Check here if it should be red or not
if (selectedButtonIndexPath == indexPath)
{
cell.button.backgroundColor = [UIColor redColor];
}
return cell;
}
And the button target action:
-(void)cellButtonPressed:(IndexPathButton*)sender
{
//Set the selectedIndexPath
selectedButtonIndexPath = sender.indexPath;
[yourTableView reloadData];
}
Following is a code fragment from cellForRowAtIndexPath. I have added 2 buttons on a Cell.
When the user clicks on Button A the image of Button A should be a.png. And Button B should change to default.png.
When the user clicks on Button B the image of Button B should be b.png. And Button A should change to default.png.
How can i do this ?
cellForRowAtIndexPath Method
[cell.aButton addTarget:self action:#selector(methodA:) forControlEvents:UIControlEventTouchUpInside];
[cell.bButton addTarget:self action:#selector(methodB:) forControlEvents:UIControlEventTouchUpInside];
- (void) methodA:(id) sender {
[((UIButton *)sender) setImage:[UIImage imageNamed:#"a.png"] forState:UIControlStateSelected];
// How to change the image of Button B to default.png ??
}
- (void) methodB:(id) sender {
[((UIButton *)sender) setImage:[UIImage imageNamed:#"b.png"] forState:UIControlStateSelected];
// How to change the image of Button A to default.png ??
}
If you have set tag to your buttons like aButton has tag= 1, and bButton has tag= 2
- (void) methodB:(id) sender {
UIButton *bButton =((UIButton *)sender) ;
[bButton setImage:[UIImage imageNamed:#"b.png"] forState:UIControlStateSelected];
UIButton *aButton = (UIButton *)[bButton.superview viewWithTag:bButton.tag-1];
[aButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateSelected];
}
- (void) methodA:(id) sender {
UIButton *aButton =((UIButton *)sender) ;
[aButton setImage:[UIImage imageNamed:#"a.png"] forState:UIControlStateSelected];
UIButton *bButton = (UIButton *)[bButton.superview viewWithTag:aButton.tag+1]; //updated here, instead of bButton, put aButton
[bButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateSelected];
}
Enjoy Coding !!
Try this,
- (void) methodA:(id) sender {
UIButton *buttonA = (UIButton *)sender;
CGPoint pointInTable = [field convertPoint:buttonA.bounds.origin toView:_tableView];
NSIndexPath *indexPath = [_tableView indexPathForRowAtPoint:pointInTable];
UITableViewCell *cell = [_tableView cellForRowAtIndexPath:nowIndex];
//now access the button and change button images
//cell.aButton setImage:
//cell.bButton setImage:
}
Do the same for button B action.
Note: I recommend using custom tableview cell and handling this button actions inside the custom cell.
For both the buttons, set a.png and default.png for UIControlStateNormal and UIControlStateSelected respectively
Now you can simply make the button selected and deselected accordingly and donot worry about the image.
Hope this image gives you another hint.
To handle your selection issue, the best way is to handle it in your tableViewCell class, where you can access both the buttons and write a delegate or callback if required.
Try this...
cellForRowAtIndexPath
[cell.aButton addTarget:self action:#selector(methodToggle:) forControlEvents:UIControlEventTouchUpInside];
[cell.bButton addTarget:self action:#selector(methodToggle:) forControlEvents:UIControlEventTouchUpInside];
[cell.aButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateNormal];
[cell.bButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateNormal];
[cell.aButton setImage:[UIImage imageNamed:#"a.png"] forState:UIControlStateSelected];
[cell.bButton setImage:[UIImage imageNamed:#"b.png"] forState:UIControlStateSelected];
cell.aButton.tag == 111;
cell.aButton.tag == 222;
Just One method for both Buttons
- (void) methodToggle:(id) sender {
UIButton * btn = (UIButton *)sender;
if (btn.tag == 111)
{
UIButton * btnAnother = (UIButton *)[[btn superview] viewWithTag:222];
btnAnother.selected = NO;
}
if (btn.tag == 222)
{
UIButton * btnAnother = (UIButton *)[[btn superview] viewWithTag:111];
btnAnother.selected = NO;
}
btn.selected = YES;
}
Inside tableView:cellForRowAtIndexPath: add following code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
[cell.aButton setTag:1];
[cell.aButton addTarget:self action:#selector(methodA:) forControlEvents:UIControlEventTouchUpInside];
[cell.aButton setTag:2];
[cell.bButton addTarget:self action:#selector(methodB:) forControlEvents:UIControlEventTouchUpInside];
}
Implement the button event handlers as-
- (void) methodA:(id) sender
{
UIView *view = [sender superView];
UIButton *senderButton = (UIButton *)sender;
[senderButton setImage:[UIImage imageNamed:#"a.png"] forState:UIControlStateSelected];
UIButton *otherButton = [view viewWithTag:2];
[otherButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateNormal];
}
- (void) methodB:(id) sender
{
UIView * view = [sender superView];
UIButton *senderButton = (UIButton *)sender;
[senderButton setImage:[UIImage imageNamed:#"b.png"] forState:UIControlStateSelected];
UIButton *otherButton = [view viewWithTag:1];
[otherButton setImage:[UIImage imageNamed:#"default.png"] forState:UIControlStateNormal];
}
Write a CustomCell class which has 2 buttons with target methods and delegate method to notify the table view when buttons clicked. Use this cell in the table view.
In target methods do the image changes(A/B) and fire the delegate method to notify the tableViewController.
You can keep indexpath as a property of cell and pass it with the delegate to tableView.(Set the indexpath for the cell in tableView's cellForRowAtIndexPath:)Then you can identify which cell's button was clicked and relevant data object can fetch from your data source.
CustomCell.m
- (IBAction)onButtonAClicked:(id)sender {
// change your images
[delegate cellButtonClicked:self.indexpath];
}
TableViewController.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CustomCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil) {
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
cell.delegate = self;
}
cell.indexpath = indexPath;
}
//delegate method
-(void)cellButtonClicked:(NSIndexPath *)indexPath{
//get the related data object for the cell using indexPath from your data source
}
I have searched all over the web and cant seem to find a solution to this simple problem. I have a table view of buttons when the work "like". When the Button is pressed, it changes the word to "Unlike". I got it to work but when I scroll down the table, I see other buttosn also change to "unlike" and sometimes overlaps it with "Like". And when I scroll back up, the original button I selected changes back to normal state. I understand the cells are reusable and thats why I am using a mutable array for my data source and still it doesnt work. Please help!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setTitle:#"Like" forState:UIControlStateNormal];
myButton addTarget:self action:#selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
myButton.tag =indexPath.row;
[cell.contentView addSubview:myButton];
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
return cell;
}
the action method:
-(void)tapped:(id)sender {
UIButton *senderButton = (UIButton *)sender;
UITableViewCell *parentCell = [[sender superview]superview];
NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];
[array replaceObjectAtIndex:senderButton.tag withObject:[NSNumber numberWithInt:1]];
[sender setTitle:#"Unlike" forState:UIControlStateNormal];
}
If the table calls the cellForRowAtIndexPath you create all the time a new button. When you get a reused cell the button still exists and you put a new one over there.
Change your method to:
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setTitle:#"Like" forState:UIControlStateNormal];
myButton addTarget:self action:#selector(tapped:) forControlEvents:UIControlEventTouchUpInside];
myButton.frame = CGRectMake(14.0, 10.0, 125.0, 25.0);
myButton.tag =indexPath.row;
[cell.contentView addSubview:myButton];
}
else {
// todo: change the button title to "like" or "unliked" value
}
cell.textLabel.text = [recipes objectAtIndex:indexPath.row];
P.S. This make no sense, you doesn't use that, why you do that?
UITableViewCell *parentCell = [[sender superview]superview];
NSIndexPath *indexPathLiked = [table indexPathForCell:parentCell];
If you have only one section you can get the cell without using superview:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0]
UITableViewCell *parentCell = [table cellForRowAtIndexPath:indexPath];
I Have a problem with my custom UItableViewCell. It's seems that all UIButton of UITableViewCell disappear on scroll. Specilay on my 25 cell. Any one have any idea ?
any help would be appreciated :)
That some code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString* cellIdentifier = #"Cell";
Cell * __strong cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell){
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
InfoObject __weak *obj = [_pos objectAtIndex:indexPath.row];
[cell configCell];
cell.id = obj.id;
{// EVENT ON BUTTON
[cell.checkbox addTarget:self action:#selector(checkup:) forControlEvents:UIControlEventTouchUpInside];
[cell.btnPaymentState addTarget:self action:#selector(changePaymentState:) forControlEvents:UIControlEventTouchUpInside];
}
{// SET BUTTON CHECKBOX
cell.checkbox.tag = indexPath.row;
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_UNCHECKBOX] forState:UIControlStateNormal];
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_CHECKBOX] forState:UIControlStateSelected];
[cell.checkbox setImage:[UIImage imageNamed:IMG_BLACK_CHECKBOX] forState:UIControlStateHighlighted];
}
{// SET BUTTON PAYMENT STATE
cell.btnPaymentState.tag = indexPath.row;
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateNormal];
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateSelected];
[cell.btnPaymentState setImage:[self getImageAssociateWithName:obj.stringPaymentState] forState:UIControlStateHighlighted];
}
[self SetSelectedBackgroundColorSelectedForFolderCellAtRow:indexPath.row
:obj.selected Cell: cell];
[cell.checkbox setSelected:obj.selected];
[self setCellColorTextOfObjectPrepare:cell withObj:obj];
return cell;
}
I solve my problem. The problem is that i was using Tag for my UIButton and the identifier was the same number tag of another UIView so when i was removing my UIView the UIButton disappear also. Thanks all for your answer.
Remove if (!cell)
And you're good to go.
i am working with the tableview in which i added 2 buttons on one cell. Below is the code which i used
- (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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
on the tickbtn and crossbtn i am applying following actions :-
-(IBAction)addshed:(UIControl *)sender
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag-200 inSection:0];
UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];
UIButton *check1 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+200];
UIButton *check2 = (UIButton*)[cell.contentView viewWithTag:indexPath.row+400];
UIImageView *btnimg1 = [[UIImageView alloc] initWithImage:check1.currentBackgroundImage];
//UIImageView *btnimg2 = [[UIImageView alloc] initWithImage:check2.currentBackgroundImage];
NSLog(#"SHED LIST subviews: %#", btnimg1.image);
// Shed_data *sheddata = [[Shed_data alloc] init];
if (btnimg1.image == [UIImage imageNamed:#"ok_gray.png"]) {
//btnimg.image = [UIImage imageNamed:#"ok_gray.png"];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_green.png"]forState:UIControlStateNormal];
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[self addsheddata:sender];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
}
else if (btnimg1.image == [UIImage imageNamed:#"ok_green.png"])
{
[check2 setBackgroundImage:[UIImage imageNamed:#"delete-red.png"]forState:UIControlStateNormal];
[check1 setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[self removesheddata:sender];
}
}
-(IBAction)removeshed:(UIControl*)sender
{
//.…………………….. My functionality
}
but in both these cases i am getting the tag value of last cell only whenever i am pressing the buttons of the cell.
Please locate my error and help me out to solve it. Your help will be much appreciable.
Try this one as working fine for me. I Just tested with my Xcode 5.
Modification :
1. I Create an NSMutableArray with the name of _objects (_objects = [[NSMutableArray alloc]initWithObjects:#"one",#"two",#"thre", nil];). and give it to my UITableView.
2.Give the tickBtn and crossBtn an different color so easily visible.
3.change the button pressed function to UIControl to UIButton like -(IBAction)addshed:(UIButton *)sender and when button pressed i catch the tag value and print it out on the console.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [_objects objectAtIndex:indexPath.row];
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn setBackgroundColor:[UIColor blackColor]];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell.contentView addSubview:tickbtn];
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[crossbtn setBackgroundColor:[UIColor greenColor]];
[cell.contentView addSubview:crossbtn];
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
-(IBAction)addshed:(UIButton *)sender {
NSLog(#"add shed %d",sender.tag);
}
-(IBAction)removeshed:(UIButton *)sender {
NSLog(#"remove %d",sender.tag);
}
NEW QUESTION UPDATE
Did you try with 10 or more cells and try with some continuous scroll?
And the result is
As the Another Answer says
[cell addSubview:crossbtn];// -------- Change here ---------
Let me clear this as i know about it.
The contentView is a subview of UITableViewCell. please review this reference and here you can see there are actually 3 subviews in a UITableViewCell.
You need to add your button to cell subview not cell's contentview subview. So use this 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];
}
cell.backgroundView =[[UIImageView alloc] initWithImage:[ [UIImage imageNamed:#"list-bg.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:5.0] ];
tickbtn = [UIButton buttonWithType:UIButtonTypeCustom];
tickbtn.tag = 200+indexPath.row;
[tickbtn setBackgroundImage:[UIImage imageNamed:#"ok_gray.png"]forState:UIControlStateNormal];
[tickbtn addTarget:self action:#selector(addshed:) forControlEvents:UIControlEventTouchUpInside];
tickbtn.frame = CGRectMake(220, 10, 30, 30);
[cell addSubview:tickbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)tickbtn.tag);
crossbtn = [UIButton buttonWithType:UIButtonTypeCustom];
crossbtn.tag = 400+indexPath.row;
[crossbtn setBackgroundImage:[UIImage imageNamed:#"delete-gray.png"]forState:UIControlStateNormal];
[crossbtn addTarget:self action:#selector(removeshed:) forControlEvents:UIControlEventTouchUpInside];
crossbtn.frame = CGRectMake(250, 10, 30, 30);
[cell addSubview:crossbtn];// -------- Change here ---------
NSLog(#"tickbtn tag %ld",(long)crossbtn.tag);
return cell;
}
Your code seems fine for cellForRowAtIndexpath:. Error might be in getting the tag value at button click. Try to change with this code:-
-(IBAction)addshed:(UIControl *)sender
{
//.…………………….. My functionality
int selectedRow1 = ((UIControl *)sender).tag;
NSLog(#"No. %d", selectedRow1);
}
I have seen issue. It may be lead to this type of error.
Why do you add subviews again and again to your cell's content view.?
That is, for every cellForRowAtIndexpath: call, button will be add to cell. In case dequeueReusableCellWithIdentifier:, your last cell may reuse to any other cell while scroll. It will lead to your error. that is your cell will contain two button.(tag with last cell and tag with your current cell).
In this line [cell.contentView addSubview:tickbtn];, you have to do some change according to add once and also for crossbtn.
Updation: I have seen your updated question. My suggestion, better use custom cell. Use this link to how to create custom cell.. Lot of confusion in your code. ex. in this line UITableViewCell *cell = (UITableViewCell*)[list_table cellForRowAtIndexPath:indexPath];, It will give unexpected. Don't call delegate method like this.