I have a UISwitch
added as a contentview
inside a UITableViewCell
.
The control works only if tapped, but if I try to drag it to the left or the right, the selector function is not called.
Any help?
I have a UISwitch
added as a contentview
inside a UITableViewCell
.
The control works only if tapped, but if I try to drag it to the left or the right, the selector function is not called.
Any help?
switch_Bool = [[UISwitch alloc]initWithFrame:CGRectMake(0,0,20,20)];
[switch_Bool addTarget:self action:@selector(actionBoolSwitch:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:switch_Bool];
It works only if i tap my UISwitch, but if i drag it, the function actionBoolSwitch is not called...
What I understood from your question is, you are trying to add a UiSwitch to table view cell.
The very first thing you need to do as a standard practice is to create a subclass of UITableViewCell, add all the components you need and then use it in cellForRowAtIndexPath.
take a look at below sample code.
//inside your cell creation block
UISwitch *mySwitch = [[UISwitch alloc] initWithFrame:CGRectMake(add coordinates here...)];
[mySwitch addTarget:self action:@selector(changeSwitch:) forControlEvents:UIControlEventValueChanged];
mySwitch.tag = indexpath.row;
[cell.contentview addSubview:mySwitch];
}
- (void)changeSwitch:(id)sender{
if([sender isOn])
{
NSLog(@"Switch is ON");
}
else
{
NSLog(@"Switch is OFF");
}
}
You may be using UIControlEventTouchUpInside
event.
Use UIControlEventValueChanged
instead, so your action is called every time the UISwitch
value changes, no matter what event was the trigger.
Try this.
To find the cell that holds the switch
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
To find the indexpath of that cell
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
- (void) switchChanged:(id)sender {
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
NSString *strCatID =[[NSString alloc]init];
strCatID = [self.catIDs objectAtIndex:indexpath];
NSLog( @"The switch for item %@ is %@",StrCatID, switchInCell.on ? @"ON" : @"OFF" );
}