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?
It is possible to trigger @selector
by adding a target to the UISwitch
.
[switchCtl addTarget:self action:@selector(action:) forControlEvents:UIControlEventValueChanged];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With