Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 795
Kent Avatar asked Feb 24 '23 08:02

Kent


2 Answers

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

[switchCtl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
like image 60
Matej Avatar answered Feb 26 '23 22:02

Matej


Another possibility is to set the tag property on the UISwitch to match the row of your tableview. If you use multiple sections as well, then you could come up with some solution to encode these in a single integer value. Keep in mind that with this approach, you need to update the tag every time you update the cell (tableView:cellForRowAtIndexPath:) since the row can change as cells are reused.

like image 45
Andrew Hershberger Avatar answered Feb 26 '23 20:02

Andrew Hershberger