I'm trying to print on/off when the user changes the state of my UISwitch.

enter image description here

For example

- (IBAction)toggleSwitch:(id)sender {

    ChannelsTableViewCell* cell = (ChannelsTableViewCell *)[sender superview].superview;
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];

    if (cell.localSwitch.on)
    {
        NSLog(@"On");
    }

}

When I run this it throws an error.

2014-04-24 11:33:41.462 HRApp[3258:60b] -[UITableViewCellScrollView localTitle]: unrecognized selector sent to instance 0x19354410 2014-04-24 11:33:41.467 HRApp[3258:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITableViewCellScrollView localTitle]: unrecognized selector sent to instance 0x19354410'

有帮助吗?

解决方案

If you hook up the IBAction to the switch, you don't need to get the UITableViewCell to check for the switch's value. You can use the sender parameter from the IBAction. Hence:

- (IBAction)toggleSwitch:(id)sender {
    UISwitch *switch = (UISwitch *)sender;
    if (switch.on)
    {
        NSLog(@"On");
    }

}

If you need to find the indexPath at which the UISwitch is shown, you can add the following:

CGPoint pointInTable = [switch convertPoint:switch.bounds.origin toView:self.tableView];    
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:pointInTable];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top