Share on Google+Share on Google+

UIButton Image Change

Ads
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

Advertisements

Posted on: May 3, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Advertisement