Trouble using UiButton as toggle switch

309 Views Asked by At

I had luck with the below code using a UISwitch to toggle. I need a UIButton to do the same. Not sure what I need to change to make that work? Thanks for any help!

- (IBAction)switchNotes:(id)sender {
    if([sender isOn]){
        NSLog(@"Switch is ON");
        for(UIButton *myButton in self.myButtonCollection) {
            [myButton setTitleColor:[BT_color getColorFromHexString:@"#FFFF00"] forState:UIControlStateNormal];
            [myButton setAlpha:1.0f];
        }
    } else{
         NSLog(@"Switch is OFF");
        for(UIButton *myButton in self.myButtonCollection) {
            [myButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
            [myButton setAlpha:1.0f];

        } 
    } 
}
2

There are 2 best solutions below

0
On

I believe your problem is that you are using the isOn property which is a property of UISwitch. According to this link iPhone UIButton with UISwitch functionality you should use the selected property of UIButton.

1
On
- (IBAction)switchNotes:(id)sender
{
    sender.selected = !sender.selected;
    if(sender.selected)
    {
        NSLog(@"Switch is ON");
        for(UIButton *myButton in self.myButtonCollection) {
            [myButton setTitleColor:[BT_color getColorFromHexString:@"#FFFF00"] forState:UIControlStateNormal];
            [myButton setAlpha:1.0f];
        }
    }
    else
    {
        NSLog(@"Switch is OFF");
        for(UIButton *myButton in self.myButtonCollection) {
            [myButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
            [myButton setAlpha:1.0f];
        }
    }
}