addTarget:action:forControlEvents - UISwitch in TableView - sender ok, event always 0x0

Kent picture Kent · May 3, 2011 · Viewed 10.1k times · Source

Using the fantastic posts in this forum, I created a switch as a accessoryView in a tableView. When the switch is touched my action (switchChanged) is called. Only the sender has a valid value, the event is 0x0.

Adding target to the switchView:

        [switchView addTarget:self action:@selector(switchChanged:forEvent:) forControlEvents:(UIControlEventValueChanged | UIControlEventTouchDragInside)];

The Action:

- (void) switchChanged:(id)sender forEvent:(UIEvent *)event {
  if(event) {
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:[[[event touchesForView:sender] anyObject] locationInView:self.tableView]];
    IFDFlightlogFormQuestions *question = [self.resultsController objectAtIndexPath:indexPath];
    NSLog(@"IFDNewFlightlogViewController_Pad:switchChanged Switch is %@ xmlAttrib %@",[sender isOn],question.XmlAttrib);
    [self.xmlResults setValue:([sender isOn])?@"true":@"false" forKey:question.XmlAttrib];
  }
}

Using action:@selector(switchChanged: forEvent:) - Added space - no change.

Using action:@selector(switchChanged::) - removed forEvent - unrecognized selector.

My goal is to get the indexPath to the tableView so I can change the value in my dictionary.

My current workaround is to use just the sender information, but I would like the event information:

- (void) switchChanged:(id)sender forEvent:(UIEvent *)event {
    UISwitch *switchView = (UISwitch *)sender;
    UITableViewCell *cell = (UITableViewCell *)switchView.superview;
    UITableView *tableView = (UITableView *)cell.superview;
    NSIndexPath *indexPath = [tableView indexPathForCell:cell];
    IFDFlightlogFormQuestions *question = [self.resultsController objectAtIndexPath:indexPath];
    NSLog(@"IFDNewFlightlogViewController_Pad:switchChanged Switch is %@ xmlAttrib %@",([sender isOn])?@"On":@"Off",question.XmlAttrib);
    [self.xmlResults setValue:([sender isOn])?@"true":@"false" forKey:question.XmlAttrib];        
}

Any pointers on getting the event information on this?

Answer

Matej picture Matej · Dec 21, 2013

It is possible to trigger @selector by adding a target to the UISwitch.

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