I have a table view, inside which there is a cell. This cell has a button which is declared like this in the customTableVIewCell class.
@property (weak, nonatomic) IBOutlet UIButton *myButton;
inside the table view controller, i am setting method for this button.
[cell.myButton setTitle:@"Show cell number!" forState:UIControlStateNormal];
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
i want to change the title of the button whenever it is selected.
Now consider this: I have three cells in my table view, that is my table has three rows. In each row, there is a button called myButton.
Whenever it is clicked, i want to change the title of the button to 1 or 2 or 3 depending on the cell number in which the button exists.
i tried this:
- (IBAction)myButtonClicked:(id)sender{
NSIndexPath *indexPath =[self.tableVIew indexPathForCell:(UITableViewCell *)[[sender superview] superview]];
NSUInteger row = indexPath.row;
NSLog(@"button was clicked for the following row %i", row);
}
But this is printing "button was clicked for the following row 0" to the console, no matter the button on cell #1 or cell #2 or cell #3 were clicked. (cell is nothing but the table row)
Please help me.
Try setting button tag as-
cell.myButton.tag = indexPath.row;
in your cellForRowAtIndexPath method..
And in your myButtonClicked method get the tag of sender button.. and then do whatever you want to do further.
- (IBAction)myButtonClicked:(id)sender{
NSLog(@"button was clicked for the following row %i", sender.tag);
}
you can just use the sender in the IBAction :)
- (IBAction)myButtonClicked:(UIButton*)sender
{
[sender setTitle:@"show new title" forState:UIControlStateNormal];
}
In the method cellForRowAtIndexPath where you initialise the cell,add this
cell.myButton.tag=indexPath.row;
[cell.myButton addTarget:self action:@selector(myButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
And update your myButtonClicked method.
- (IBAction)myButtonClicked:(id)sender{
UIButton *btn=sender;
NSLog(@"button was clicked for the following row %i", btn.tag);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.