Home Tutorial Iphone Examples UIButton Image Change

 
 

UIButton Image Change
Posted on: May 3, 2010 at 12:00 AM
In this series of iPhone UIButton examples, we are going to discuss about UIButton and how to get the image changed on button clicks.

UIButton Image Change

In this series of iPhone UIButton examples, we are going to discuss about UIButton and how to get the image changed on button clicks. Although you can also use interface builder, which makes the task easy and fast but... in this UIButton example everything is done programmatically from creating a button to changing images on button action.

To change the image on button action, we are going to use two type of controls "UIControlStateNormal" and "UIControlStateSelected" that drives from it's base class UIControl. In iPhone control could be any a button or switch button and that control can have more then one state at a time.

As in this example we are creating a button that has two different states, selected and normal that will be recognized differently depending on the button control. We are also going to take a action on button that will recognize and set the state of button on clicking it.

UIControlStateNormal: by default every control has the Normal state. When a control is in its normal state we say that it's neither selected nor highlighted. Where as UIControlStateSelected is the selected state of a control.

Syntax
Creating and setting default state of the UIButton

- (void)drawButton
{
myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(80, 50, 70, 70); //set frame for button

UIImage *buttonImage = [UIImage imageNamed:@"icon6.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

[myButton setTitle:@"Ok" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:myButton];

}

"myButton" is the object of UIButton class that is already declared into the interface (ViewController.h) file.

Code to change image on Button Action

- (IBAction)buttonClicked:(id)sender
{

if (myButton.selected=YES)
{
UIImage *buttonImage = [UIImage imageNamed:@"home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateSelected];

}else{

UIImage *buttonImage = [UIImage imageNamed:@"icon6.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
}
}

On running the application.. it will look like the given Image..

Normal or default state of button

Selected State of button

Download Code

Related Tags for UIButton Image Change:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.