X-Cake

Cocoaheads Ireland and Northern Ireland

Adding a Dynamic Custom Title to a modal view's Navigation Bar

Adding a Dynamic Custom Title to a modal view's Navigation Bar

I've seen this issue come up a couple of times recently and figured I'd share a solution to it here.

It probably isn't the best way of achieving this, so if anyone has a better solution, feel free to comment :)


First, create your modal view controller (with a .xib) - I've used the name MyModalView for this example.

Open up the xib in Interface Builder and drag a navigation bar onto the view. Next delete the Title text from the nav bar.

Drag a label into place over where the Title text should go and customise the font to your liking.


What we want to do next is create a property in our MyModalView class that allows us to set the custom title.

Header:

@interface MyModalView : UIViewController {

IBOutlet UILabel* barTitle;

NSString* customTitle;
}

@property(nonatomic,retain) NSString* customTitle;

@end



Implementation file:

@implementation MyModalView

@synthesize customTitle;

- (void)viewDidLoad {

...

barTitle.text = self.customTitle;

}

- (void)dealloc {

[self.customTitle release];

...
}


Creating the Modal View:

When that's done, save all your files and link the UILabel outlet to the label in Interface Builder.


Now, wherever we are presenting the modal view, we can now simply do the following:

MyModalView* mv = [[[MyModalView alloc] initWithNibName:@"MyModalView" bundle:nil] autorelease];

mv.customTitle = @"Some Title";

[self presentModalViewController:mv animated:YES];


And it will display your custom modal view with the "Some Title" text on the navigation bar.

Views: 644

Tags: code, modal, navigation, title, uilabel, uinavigationbar, view

Comment

You need to be a member of X-Cake to add comments!

Join X-Cake

Comment by Vinny Coyne on October 28, 2009 at 11:42am
Awesome, thanks Daniel! :)
Comment by Daniel Heffernan on October 26, 2009 at 1:45pm
np! And it doesn't even have to be set before displaying it either: you can do it while on the screen just fine and it will update reliably.
Comment by Vinny Coyne on October 26, 2009 at 10:27am
Thanks Daniel, I knew there had to be a better way!

All you'd need to do then is set either the nav bar or an NSString as a property and set the new value before displaying the modal view.
Comment by Daniel Heffernan on October 23, 2009 at 5:37pm
If you have a UINavigationBar in IB it will have a default UINavigationItem that you can access. Why not just have an IBOutlet from the file's owner to that UINavigationItem?

@interface MyModalView {
IBOutlet UINavigationItem *myItem;
}

@implementation MyModalView
- (void)viewDidLoad {
...
myBar.title = @"New title!";
}

© 2013   Created by Matt Johnston.   Powered by

Badges  |  Report an Issue  |  Terms of Service