Reputation: 2022
I create tow or more custom cell
each cell has a switch inside
How can I know which switch in the row I click
ex.I click the switch in row 3,than It will return indexPath.row = 3
and also the switch status is on or off ?
which void I should put in ?
I know there is a way can get indexpath return by:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
But I don't want to touch the row,just the switch ...
Oh I do some research but it just be a little different
How can keep track of the index path of a button in a tableview cell?
any ideas ?
I wish I can post my screen shot,but not I am a new user the system doesn't allow me to do this
Upvotes: 2
Views: 1114
Reputation: 4901
When you create the switch, set up a target and action for it:
[mySwitch addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
Here, the target self
is your UITableViewController
, in which you'll need to implement the method (void) switchToggled:(id)sender
to handle the control event. The switch will automatically send itself to the switchToggled
method as the sender
when it is toggled. Like this (modified from the UIButton
example you linked):
- (void)switchToggled:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)theSwitch.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
if(theSwitch.on) {
// switch turned on
}
else {
// switch turned off
}
}
Upvotes: 3
Reputation: 33345
When button is created
button.tag = [indexPath row]
When button is selected, pull the row out of the tag
int myRow = [(UIButton *)sender tag];
Upvotes: 1