Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

toggle UIButton-state when pressing, like a switch

-(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 ?

like image 262
nico Avatar asked Jul 21 '10 14:07

nico


People also ask

How do I toggle a button in Swift?

How do you toggle a button in Swift? You can create a toggle or switch by simply typing Toggle() . To configure toggle, we have to pass the parameter. The parameter name is isOn of type Binding<Bool> , which defines the state of the toggle (i.e., whether it's on or off).

What is a UIButton?

A control that executes your custom code in response to user interactions.


2 Answers

Try this way:

-(void)setState:(id)sender
{
    UIButton* button = (UIButton*)sender;
    button.selected = !button.selected;
}
like image 78
Vladimir Avatar answered Oct 26 '22 12:10

Vladimir


Swift 3 way:

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

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

like image 43
finneycanhelp Avatar answered Oct 26 '22 13:10

finneycanhelp