iPhone, iPod touch, iPad tutorials, examples and sample code. Come and get it!

Thursday, August 12, 2010

UIButton with custom UIImage

Most developers want to steer clear of the default buttons provided in Cocoa because they're just not that attractive. The following code shows how to programmatically create an image button and define an action for when the button is pressed.
// Create button and set frame
UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
// Set button image, in this case "my_image.png"
[myButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"my_image" ofType:@"png"]] forState:UIControlStateNormal];
// Call buttonWasPressed function when button is touched
[myButton addTarget:self action:@selector(buttonWasPressed) forControlEvents:UIControlEventTouchUpInside];
// Add the button to view
[self.view addSubview:myButton];

Labels: , ,


Post a Comment

Subscribe to Post Comments [Atom]

<< Home

« Older Entries  
Newer Entries »