Search code examples
uitableviewuiswitchuicontrol

UISwitch not changing value


I added a UISwitch to a UITableViewCell in code, and added a target/action. The problem is that when the UISwitch is touched, it starts to animate to the opposite value, buy then stops animating and returns to the previous value. So basically the slider will slide 75% of the way from OFF to ON, and then go back to OFF, so I can't switch it. Once it is switched, I add a section to the UITableView, and I don't know why this isn't working. Can someone tell me if there is anything wrong with my code?

Here is where I add the UISwitch:

self.forSaleSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(223.0f, 8.5f, 0.0f, 0.0f)];
                [self.forSaleSwitch addTarget:self
                                       action:@selector(switchTapped:)
                             forControlEvents:UIControlEventValueChanged];
                self.forSaleSwitch.backgroundColor = [UIColor clearColor];
                self.currentAnnotation.isHouseForSale = (self.forSaleSwitch.on) ? YES : NO;

                [cell addSubview:self.forSaleSwitch];

And here is the action for the UISwitch:

- (void)switchTapped:(id)sender
{
    UISwitch *switcher = (UISwitch *)sender;
    if (switcher.on)
    {
        [switcher setOn:NO animated:YES];
        self.currentAnnotation.isHouseForSale = NO;
        NSLog(@"OFF");
    }
    else
    {
        [switcher setOn:YES animated:YES];
        self.currentAnnotation.isHouseForSale = YES;
        NSLog(@"ON");
    }
    [self.tableView reloadData];
}

Solution

  • When you call the reloadData method you're asking the table view to refresh and reload all the cells. If you're not storing the value of the switch somewhere and then restore it when the cell is created, then it will always return to its default state, which is NO.