tags:

views:

820

answers:

3

Hello all,

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.

A: 

Change button image isn't a difficult task. And you can use some BOOL value to detect if your switch-button is in "ON" state. and in your onBtnClk method you can just change state of your BOOL value and set image for current state.

Morion
well yeah, but this way we are changing the image every time. Is there any way where we dont have to change it on every click and just assign it at the start.
rkb
I cannot understand why it so difficult to change image? and to your question, if there is any way to assign this behavior only once, I don't know it.
Morion
+2  A: 

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){
    toggleIsOn = NO;
    [self.toggleButton setImage:[UIImage imageNamed:@"off.png"] forState:UIControlStateNormal];
    //do anything else you want to do.
  }
  else {
    toggleIsOn = YES;
    [self.toggleButton setImage:[UIImage imageNamed:@"on.png"] forState:UIControlStateNormal];
    //do anything you want to do.
}

then link your button with the IBActions and the IBOutlet and initialize toggleIsOn to NO.

Dimitris
A: 

I believe this post has a better solution : http://stackoverflow.com/questions/2255166/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.

Lee Probert