domesticcatsoftware / DCRoundSwitch

A 'modern' replica of UISwitch.
MIT License
765 stars 162 forks source link

Switch In Custom Cell Fires On Table Reload #27

Open bchristopher opened 12 years ago

bchristopher commented 12 years ago

Hi,

I have a UITableView containing four rows. Each row has a custom cell with a DCRoundSwitch. The value-changed event is linked in IB to a switchChanged method. Each time a new cell with a switch is needed in cellForRowAtIndexPath I assign the new cell's switch to an ivar so I can control it programmatically like this:

       self.categorySwitch = ((FilterViewCell *)cell).sectionSwitch; 

The problem: After I change a switch the first time it works perfectly, triggering the switchChanged method. Thereafter, every time a new cell is needed or the table is reloaded, it fires off the switchedChanged method without touching the switch. I've tried the removing all targets at the end of the switchChanged method like so but it still didn't work:

       [theSwitch removeTarget:nil action:NULL forControlEvents:UIControlEventAllEvents];

This works perfectly using UISwitch.

Any suggestions? DCRoundSwitch appears to be an excellent alternative and I would like to use it.

Thanks

ablackwoodim3 commented 11 years ago

DCRoundSwitch fires events for UIControlEventValueChanged even when the value is changed programmatically, rather than only when the user toggles the switch, as UISwitch does. I imagine that you're initializing the new cell's switch to the correct value, which fires the switchChanged method.

To make it behave like UISwitch, you can change the setOn:animated: method so that control events are not sent:

- (void)setOn:(BOOL)newOn animated:(BOOL)animated
{
    [self setOn:newOn animated:animated ignoreControlEvents:YES];
}

Remember to change the calls to setOn:animated: within tapped: and toggleDragged: so that they call setOn:animated:ignoreControlEvents: and pass true to the ignoreControlEvents parameter.