toggle UIButton-state when pressing, like a switch
Asked Answered
W

2

7
-(void)setState:(id)sender
{
    UIButton* button = (UIButton*)sender;
    BOOL buttonBool = ([button state]==selected : YES ? NO);
    [sender setSelected:buttonBool++];

}

this is my idea, but i cant figure out the actual state of the button calling the funktion. any button, that calls this funktion, should be toggled between default and selected-state, so that it works like a switch. i just need to have own background-graphics, else i had used a switch.

so, can anyone please correct my idea ?

Womankind answered 21/7, 2010 at 14:49 Comment(0)
C
20

Try this way:

-(void)setState:(id)sender
{
    UIButton* button = (UIButton*)sender;
    button.selected = !button.selected;
}
Choroid answered 21/7, 2010 at 14:51 Comment(3)
oh.. that was too simple ! i think that this works, how i want it to work, thank you. i´ll try it tomorrow Message: You can accept an answer in 8 minutes so tomorrow i´m going to accept thisWomankind
Yeah, this is the smart way of programming +1 !Dekko
I don't understand why Apple didn't make this a built-in method for UIButton. It is such a common use case, and a simple - (void)toggleSelected:(UIButton *)sender would make things a bit easier for a lot of people. For anyone who has lots of buttons that need to be toggled in their application, it might make sense to create a category on UIButton called UIButton+Toggle or something, and extend UIButton to add this functionality.Barnett
L
1

Swift 3 way:

func setState(button: UIButton) {
    button.isSelected = !button.isSelected
}

(Thanks to @nadi-hassan for the Swift 3 tip.)

Lanielanier answered 3/5, 2015 at 2:2 Comment(2)
swift 3 renamed "selected" to "isSelected"Turkoman
Thanks @NadiHassanLanielanier

© 2022 - 2024 — McMap. All rights reserved.