4

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?

Simon Adcock
  • 3,554
  • 3
  • 25
  • 41
yax
  • 123
  • 1
  • 13

4 Answers4

2
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...

yax
  • 123
  • 1
  • 13
1

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");
   }

 }

Also take a look at this link

Community
  • 1
  • 1
iLearner
  • 1,670
  • 2
  • 19
  • 45
1

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.

Alvaro
  • 1,188
  • 13
  • 21
-2

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" );
        }
Shardul
  • 4,266
  • 3
  • 32
  • 50