Friday, February 12, 2010

Load background image of Button using programing code

There is a method called viewDidLoad in the controller's super class. It will be called after our view loaded. We can override it to do something after the view had been loaded, such as load background image to a button.



- Start a new iPhone OS Application using View-Based Application Template. Add a Button using Interface Builder. Assign the Tag of the button, say 10.

- Drag a image into the Resources folder. eg. Home.png, it will be our background image of the button.

- Modify our ViewController.m, un-comment the method viewDidLoad and add the code below.

- (void)viewDidLoad {
UIImage *buttonImage_Home = [UIImage imageNamed:@"Home.png"];
UIImage *stretchableButtonImageNormal = [buttonImage_Home stretchableImageWithLeftCapWidth:12 topCapHeight:0];
UIButton *homeButton = (UIButton *)[self.view viewWithTag:10];
[homeButton setBackgroundImage:stretchableButtonImageNormal forState:UIControlStateNormal];
}