iOS Passing argument to selector with addtarget

you have a switcher object named switcher


switcher.tag = indexPath.row;

[switcher addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];


- (void) switchChanged:(id)sender{
   UISwitch *switchControl = sender;
   
   NSInteger idx = switchControl.tag;
   
   NSLog(@"%d switch to %@",idx,switchControl.on ? @"Y": @"N");
}



if you use tableview, you can also use this function instead

- (void) switchChanged:(id)sender{
UISwitch *switchControl = sender;


   UITableViewCell *parentCell = (UITableViewCell *)[[switchControl superview] superview];
   NSIndexPath *indexPath = [self.myTableView indexPathForCell:parentCell];
   
   NSLog(@"row %d clicked",indexPath.row);
}

0 意見: