iosobjective-cuicontrolevents

Listen user performed state changes on an iOS Switch


In my iOS application I have UITableView and in some of the cells are a Switch.

I have set a Listener on the Switch in the following way:

[cell.toggle addTarget:self action:@selector(onSwitchToggle:) forControlEvents:UIControlEventValueChanged];

The switch state can also be updated from the program itself and not only by the user pressing it. I'm experiencing some issues with UIControlEventValueChanged and sometimes it seems to fire way more events than it should. So I'm wondering if this is the only way to listen to the Switch state changes (by the user)...?


Solution

  • I'm guessing that you are setting the addTarget inside cellForRowAtIndexPath and that's your main problem.

    Reusing the cells (scrolling for example) will add that target to a specific cell multiple times.

    Fastest solution would be to change your code to this:

    [cell.toggle removeTarget:nil 
                       action:NULL 
             forControlEvents: UIControlEventValueChanged];
    [cell.toggle addTarget:self action:@selector(onSwitchToggle:) forControlEvents:UIControlEventValueChanged]; 
    

    Which will basically prevent the target to be added more than once to the toggle. Not the prettiest solution but it's something to consider.

    A few better solutions that comes to mind: