Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a UIButton as a toggle switch

Tags:

iphone

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.

like image 720
rkb Avatar asked Nov 09 '09 16:11

rkb


People also ask

How do I use toggle 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). Inside the toggle body, we can define the text that'll appear beside the toggle view.

What is the difference between switch and toggle?

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.


2 Answers

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.

like image 166
Lee Probert Avatar answered Oct 08 '22 20:10

Lee Probert


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.

like image 44
Dimitris Avatar answered Oct 08 '22 20:10

Dimitris