I have a tableview with custom UITableViewCell. Cell have a UISwitch
controls. I have added cell into the table view controller with the same action for all switches. I have added tag value of UISwitch
in cellForRowAtIndexPath
method.
I want to determine what switch was changed, when user changed the switch status on/off. Here I am setting action on UISwitch
button.
- (void)viewDidLoad
{
[super viewDidLoad];
cell.switchbtn.userInteractionEnabled=YES;
[cell.switchbtn setOn:YES];
[cell.switchbtn addTarget:self action:@selector(switchToggled:) forControlEvents: UIControlEventValueChanged];
[cell.contentView addSubview:cell.switchbtn];
}
Here I am setting tag value of uiswitch
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=@"cellid";
cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (!cell)
{
[[NSBundle mainBundle] loadNibNamed:@"cellid" owner:self options:nil];
}
cell.switchbtn.tag=indexPath.row;
NSLog(@"btn tag=%d",cell.switchbtn.tag);
return cell;
}
Here I am calling switchToggled: method to get the uiswitch status.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
[self switchToggled:cell.switchbtn];
}
I am gettting tag value and each time status is On .even i status is off.
- (void) switchToggled:(UISwitch *)sender {
UISwitch *mySwitch = (UISwitch *)sender;
NSLog(@"tag ==%@",mySwitch);
if ([mySwitch isOn]) {
NSLog(@"its on!");
} else {
NSLog(@"its off!");
}
}