Home Tutorial Iphone Examples setBackgroundImage UIButton


Share on Google+Share on Google+
setBackgroundImage UIButton
Posted on: May 4, 2010 at 12:00 AM
In this example, we are going to discuss about how to set the background image to a UIButton in iPhone.

setBackgroundImage UIButton

In this example, we are going to discuss about how to set the background image to a UIButton in iPhone.

In the iPhone application programming, you can play with the controls in various ways ..for example you can resize the button or can set background image to it for different states. To set the background image of UIButton follow the given method...

- (void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

Here state suggest the particular state of controls, wether it's selected, highlighted or in a normal state. By default it's nil or in a normal state. You can write it as "UIControlStateNormal".

In this iPhone example, we are creating and setting Background Image on UIButton programatically. Syntax is given below...

- (void)viewDidLoad {
[super viewDidLoad];

UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
myButton.frame = CGRectMake(80, 50, 70, 70); //set frame for button

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];

[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

[myButton setTitle:@"Hello!" forState:UIControlStateHighlighted];
// add targets and actions
[myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];


On running the application you'll get the following output.

You can also set title to your button as i did on highlighting. That means when a touch up will occur on button it will show the title. Syntax is given below.

[myButton setTitle:@"Hello!" forState:UIControlStateHighlighted];

Download Code


Related Tags for setBackgroundImage UIButton:

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.

Posted on: May 4, 2010

Recommend the tutorial

Advertisements Advertisements