Cocoa-Matic

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

Wednesday, January 12, 2011

Replace UINavigationBar background with image

Sometimes you want to show off some creativity in your apps. One of the easiest ways to do that is by changing the look of the UINavigationBar. Modifying the color is one way and is a trivial task in Interface Builder. What about replacing it entirely with an image? Turns out that's not too difficult either. Here's how...

We're going to use Categories. What are Categories?
From CocoaDevCentral.com: Categories are one of the most useful features of Objective-C. Essentially, a category allows you to add methods to an existing class without subclassing it or needing to know any of the details of how it's implemented.

This is particularly useful because you can add methods to built-in objects. If you want to add a method to all instances of NSString in your application, you just add a category. There's no need to get everything to use a custom subclass.


Read more »

Labels: , , ,

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: , ,


« Older Entries