Modern approach
The modern way, for the entire navigation controller… do this once, when your navigation controller's root view is loaded.
[self.navigationController.navigationBar setTitleTextAttributes:
@{NSForegroundColorAttributeName:[UIColor yellowColor]}];
However, this doesn't seem have an effect in subsequent views.
Classic approach
The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):
You need to use a UILabel
as the titleView
of the navigationItem
.
The label should:
- Have a clear background color (
label.backgroundColor = [UIColor clearColor]
).
- Use bold 20pt system font (
label.font = [UIFont boldSystemFontOfSize: 20.0f]
).
- Have a shadow of black with 50% alpha (
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]
).
- You'll want to set the text alignment to centered as well (
label.textAlignment = NSTextAlignmentCenter
(UITextAlignmentCenter
for older SDKs).
Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.
I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)
If you want to verify this, drop this code into initWithNibName:bundle:
in PageThreeViewController.m
of Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// this will appear as the title in the navigation bar
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = NSTextAlignmentCenter;
// ^-Use UITextAlignmentCenter for older SDKs.
label.textColor = [UIColor yellowColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(@"PageThreeTitle", @"");
[label sizeToFit];
}
return self;
}
Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.