Access UISwitch in Prototype Cell

2019-09-06 22:55发布

问题:

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

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'

回答1:

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];