I am using a UIButton of custom type and what I want is use it like a toggle switch with the change of image. Like when it is clicked if previously it was not in selected mode it should go in selected mode or otherwise vice-a-versa. Also it will have a different image and when it is selected it will have a different image when it is not.
I am not able to do it programatically, is there any good easy way to do this.
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). Inside the toggle body, we can define the text that'll appear beside the toggle view.
First, we need to make a distinction between a toggle button and a toggle switch since they both manage states, but not exactly in the same way: Toggle button: Represents an action that changes a state. Toggle switch: Represents two (or more) mutually exclusive states or options that can be switched.
I believe this post has a better solution : iPhone UIButton with UISwitch functionality
UIButton has toggling built in. There is a selected property that you can set and change the skins based on the state.
In your header file add:
IBOutlet UIButton *toggleButton; BOOL toggleIsOn; @property (nonatomic, retain) IBOutlet UIButton *toggleButton;
In the implementation:
- (IBACtion)toggle:(id)sender { if(toggleIsOn){ //do anything else you want to do. } else { //do anything you want to do. } toggleIsOn = !toggleIsOn; [self.toggleButton setImage:[UIImage imageNamed:toggleIsOn ? @"on.png" :@"off.png"] forState:UIControlStateNormal]; }
then link your button with the IBActions and the IBOutlet and initialize toggleIsOn
to NO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With