289

It seems the iOS Navigation Bar title color is white by default. Is there a way to change it to a different color?

I am aware of the navigationItem.titleView approach using an image. Since my design skills are limited and I failed to get the standard glossy, I prefer changing the text color.

Any insight would be much appreciated.

Cal
  • 422
  • 6
  • 20
  • I just posted a piece of code, based on Steven Fisher's answer, that simplifies the process of adding custom colored titles to your navigation bar. It also supports changing the title. Look for it! It won't disappoint you. – Erik B May 05 '11 at 13:57
  • 1
    Erik: I've put a note about your answer into mine. I'd just update my answer with your code, but I wouldn't want to take your up votes. Clever solution, btw. – Steven Fisher Aug 19 '11 at 19:08
  • For IOS 13 https://stackoverflow.com/a/61141195/6108739 – Vladyslav Panchenko Apr 10 '20 at 13:23

32 Answers32

424

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.

Steven Fisher
  • 44,462
  • 20
  • 138
  • 192
  • I am amazed at how accurately you have reproduced the effect. Must have taken a lot of trial and error. Vote up and many thanks! – Chintan Patel Jun 03 '10 at 07:42
  • Just to add, i think using frame width as 320 instead of 400 should also do as thats the max width in vertical orientation. – Chintan Patel Jun 03 '10 at 07:55
  • Good idea, Casebash. Added to answer. – Steven Fisher Sep 23 '10 at 20:18
  • Note that this does not work with `UIViewController`s created inside interface builder (and using a custom subclass of course). The function is called, but for some reason, the custom view does not appear. – Casebash Sep 24 '10 at 02:20
  • I'll have to try that out, Casebash. I'm pretty sure that's how I was using it. It's not impossible that something's changed, though. – Steven Fisher Sep 24 '10 at 17:07
  • when i use this code, and i set the `backgroundColor` to `blackColor`, the background does not fill up the entire width of the screen. i have tried changing the width, and it does not budge. ugh! – james Nov 12 '10 at 21:40
  • 2
    If you set the label frame to the size of its text using `sizeWithFont:`, it will magically take on the automatic alignment behaviour of the standard label. – grahamparks Feb 11 '11 at 23:24
  • @grahamparks +1 ...or [label sizeToFit] after setting text. – Adolfo Mar 26 '11 at 18:34
  • 1
    But if you use sizeToFit, you'll lose automatic truncation. – Steven Fisher Mar 27 '11 at 17:59
  • Hi, My problem here is: the text is not exactly in the center! because I got a back button in the left!, so the label your creating doesnt have the whole nav bar width! What Can I do?! – Arthur Neves May 13 '11 at 16:59
  • 3
    NOTE: this is the old way to set custom title, I suggest to read answer of Erik B. – Elia Palme Aug 18 '11 at 08:51
  • 1
    Confirmed that sizeToFit works, so updated answer. Also, added note to read Erik B's answer. – Steven Fisher Aug 19 '11 at 19:05
  • Used this with - (void) setTitle:(NSString *)title { [((UILabel*)self.navigationItem.titleView) setText:title]; [((UILabel*)self.navigationItem.titleView) sizeToFit]; } – richy Aug 02 '12 at 06:01
  • 1
    label.textAlignment = UITextAlignmentCenter has been depricated since iOS6.0, use NSTextAlignmentCenter instead – Jasper Feb 07 '13 at 12:12
  • @skywinder, @kocko, @andre-dion, @stephane-bruckert: The edit you made/approved was precisely incorrect. Please be more careful. `UITextAlignmentCenter` is deprecated, not `NSTextAlignmentCenter`. – Steven Fisher Oct 11 '13 at 16:39
  • Feel bad for voting this down, but Alex answer should really be on top. – skagedal Aug 21 '15 at 06:35
  • I think that's by definition abuse of the system. – Steven Fisher Aug 21 '15 at 16:20
  • I still think this is abuse of the system, but you do have a good point. I think the best thing is probably for me to delete this answer. I'll do that in a few days to make sure you see this. :) – Steven Fisher Aug 21 '15 at 16:30
  • Actually, I'm not sure Alex's answer *is* better. Replacing the label is more light-weight than changing the system's appearance proxy (which affects ALL navigation labels). What do you think, skagedal? – Steven Fisher Aug 21 '15 at 16:31
  • Looks like you can set it directly on the navigation toolbar, but that's still shared between view controllers. I'll see what else I can think of. – Steven Fisher Sep 01 '15 at 19:10
  • what the hell!!! why do [navigationController.navigationBar setTitleTextAttributes: @{NSForegroundColorAttributeName:[UIColor whiteColor]}]; works BUT NOT [navigationController.navigationBar setTintColor : [UIColor whiteColor]] – smoothumut Jun 16 '16 at 11:31
226

I know this is a pretty old thread, but I think it would be useful to know for new users that iOS 5 brings a new property for establishing title properties.

You can use UINavigationBar's setTitleTextAttributes for setting the font, color, offset, and shadow color.

In addition you can set the same default UINavigationBar's Title Text Attributes for all the UINavigationBars throughout your application.

For example like so:

NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                            [UIColor whiteColor],UITextAttributeTextColor, 
                                            [UIColor blackColor], UITextAttributeTextShadowColor, 
                                            [NSValue valueWithUIOffset:UIOffsetMake(-1, 0)], UITextAttributeTextShadowOffset, nil];

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
Bhavin Ramani
  • 3,221
  • 5
  • 30
  • 41
Alex R. R.
  • 2,992
  • 1
  • 18
  • 13
  • 11
    'UITextAttributeTextColor' is deprecated in iOS 7. The iOS 7 key is 'NSForegroundColorAttributeName' – Keller Dec 30 '13 at 18:32
  • 1
    Note that this will change ALL navigation bars, which is usually what you'd want anyway. – Ash Feb 21 '14 at 11:22
  • 1
    Please mark this as the correct answer - the UILabel method above is unnecessary with these methods available. – Mic Fok Jun 08 '14 at 05:06
180

In iOS 5 you can change the navigationBar title color in this manner:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
mxcl
  • 26,392
  • 12
  • 99
  • 98
minux
  • 2,694
  • 2
  • 18
  • 16
  • 8
    @BartSimpson I agree! For iOS 7, update `UITextAttributeTextColor` to `NSForegroundColorAttributeName`. Works like a charm! – John Erck Sep 29 '13 at 16:21
  • THIS WORKS! what I want to understand is how?! titleTextAttributes excepts a dictionary with a predefined set of keys mentioned in 'Keys for Text Attributes Dictionaries' mentioned under 'NSString UIKit Additions Reference'. How does it take the key you mentioned. – AceN Apr 01 '15 at 19:00
  • ... and since it is working, How do i get the 'default' tint? – AceN Apr 01 '15 at 19:01
  • Setting ```self.navigationController.navigationBar.tintColor``` didn't work for me. This did. – JRam13 Jul 08 '15 at 23:11
128

Based on Steven Fisher's answer I wrote this piece of code:

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];

        titleView.textColor = [UIColor yellowColor]; // Change to desired color

        self.navigationItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = title;
    [titleView sizeToFit];
}

The advantage of this code, besides dealing with the frame properly, is that if you change the title of your controller the custom title view will also get updated. No need to update it manually.

Another big advantage is that it makes it really simple to enable custom title color. All you need to do is to add this method to the controller.

Erik B
  • 40,889
  • 25
  • 119
  • 135
  • 3
    I agree this one is definitively the best solution. No need to use sizeWithFont, and I like the idea of overriding the setTitle method. – Elia Palme Aug 18 '11 at 08:49
  • @Sr.Richie You shouldn't put the code in a custom navigation controller. You should put it in all view controllers where you need to change the color of the title. You probably don't even want a custom navigation controller. – Erik B Nov 11 '11 at 17:09
  • Doesn't work for me. I think its because I used [UINavigationBar appearance] method.. (doesn't work because the label titleView is always nil) – Matej Aug 09 '12 at 22:17
  • 1
    If you're on iOS5 or later, you should read minus's answer below. There's a one-liner that works fine and stays on the reservation. – algal Oct 10 '12 at 21:21
  • we need to add self.title=@"our string"; in viewDidLoad.then only above code works. – Hari1251 Sep 03 '14 at 11:15
40

Most of the above suggestions are deprecated now, for iOS 7 use -

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys: 
                               [UIColor whiteColor],NSForegroundColorAttributeName, 
                               [UIColor whiteColor],NSBackgroundColorAttributeName,nil];

self.navigationController.navigationBar.titleTextAttributes = textAttributes;
self.title = @"Title of the Page";

Also, checkout the NSAttributedString.h for various text properties that could be set.

girish_vr
  • 3,041
  • 1
  • 24
  • 27
38

In IOS 7 and 8, you can change the Title's color to let's say green

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
Pramesh
  • 1,194
  • 12
  • 16
  • 6
    Swift: `self.navigationController!.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as [NSObject : AnyObject]` – Byron Coetsee Apr 24 '15 at 10:17
  • @ByronCoetsee after update to Swift 2 I have the following error: Cannot assign a value of type '[NSObject : AnyObject]' to a value of type '[String : AnyObject]?' – Jorge Casariego Oct 23 '15 at 15:31
  • 2
    Alot easier in swift 2.0 `self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]` – Kevin DiTraglia Dec 10 '15 at 20:40
24

To keep the question up-to-date, I'll add Alex R. R. solution, but in Swift:

self.navigationController.navigationBar.barTintColor = .blueColor()
self.navigationController.navigationBar.tintColor = .whiteColor()
self.navigationController.navigationBar.titleTextAttributes = [
    NSForegroundColorAttributeName : UIColor.whiteColor()
]

Which results to:

enter image description here

Michal
  • 15,429
  • 10
  • 73
  • 104
  • Hmmm, maybe it doesn't work for Swift 2.0. Let me doublecheck. No need for aggression though. – Michal Sep 26 '15 at 19:16
  • Sorry Michal, I was thinking that as a joke! Not as something agressive! What worked for me was more like this: self.navigationController!.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as [NSObject : AnyObject] – Radu Sep 26 '15 at 21:14
  • Add this following line: UINavigationBar.appearance().barStyle = UIBarStyle.Black Before this line: UINavigationBar.appearance().tintColor = UIColor.whiteColor() To make tintColor work! – triiiiista May 26 '16 at 14:52
  • 2
    In Swift 4.0: self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white] – Abhi Muktheeswarar Apr 03 '18 at 07:57
14

Swift Version

I found most of you guys presented the answers of Objective_C version

I would like to implement this function by using Swift for anyone who needs it.

In ViewDidload

1.To make NavigationBar background becomes color (for example: BLUE)

self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()

2.To make NavigationBar background becomes Image (for example : ABC.png)

let barMetrix = UIBarMetrics(rawValue: 0)!

self.navigationController?.navigationBar
      .setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)

3.To change NavigationBar title (for example :[Font:Futura,10] [Color:Red])

navigationController?.navigationBar.titleTextAttributes = [
            NSForegroundColorAttributeName : UIColor.redColor(),
            NSFontAttributeName : UIFont(name: "Futura", size: 10)!
        ]

(hint1: don't forget the "!" mark after the UIFont)

(hint2: there are lots of attributes of the title text, command click the "NSFontAttributeName" you can enter the class and view keyNames and the Objects types they required)

I hope I can help!:D

Microos
  • 1,728
  • 3
  • 17
  • 34
14

Method 1, set it in IB:

enter image description here

Method 2, one line of code:

navigationController?.navigationBar.barTintColor = UIColor.blackColor()
fujianjin6471
  • 5,168
  • 1
  • 36
  • 32
13

From iOS 5 onwards we have to set title text color and font of navigation bar using titleTextAttribute Dictionary(predefined dictionary in UInavigation controller class reference).

 [[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor blackColor],UITextAttributeTextColor, 
[UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];
Hiren
  • 12,720
  • 7
  • 52
  • 72
Sandeep
  • 1,094
  • 9
  • 6
13

The solution by tewha works well if you are trying to change the color on a page, but I want to be able to change the color on every page. I made some small modifications so that it would work for all pages on a UINavigationController

NavigationDelegate.h

//This will change the color of the navigation bar
#import <Foundation/Foundation.h>
@interface NavigationDelegate : NSObject<UINavigationControllerDelegate> {
}
@end

NavigationDelegate.m

#import "NavigationDelegate.h"
@implementation NavigationDelegate

- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text?
    UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor yellowColor];
    //The two lines below are the only ones that have changed
    label.text=viewController.title;
    viewController.navigationItem.titleView = label;
}
@end
Casebash
  • 114,675
  • 90
  • 247
  • 350
10

Short and sweet.

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
Pier-Luc Gendreau
  • 13,553
  • 4
  • 58
  • 69
10

Use the code below in any view controller viewDidLoad or viewWillAppear method.

- (void)viewDidLoad
{
    [super viewDidLoad];

    //I am using UIColor yellowColor for an example but you can use whatever color you like   
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

    //change the title here to whatever you like
    self.title = @"Home";
    // Do any additional setup after loading the view.
}
App Dev Guy
  • 5,396
  • 4
  • 31
  • 54
Gaurav Gilani
  • 1,584
  • 14
  • 18
8

This is my solution based upon Stevens

Only real difference is I put some handling in for adjust the position if depending on the text length, seems to be similar to how apple do it

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f];
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft);
titleLabel.textColor = [UIColor redColor];
titleLabel.text = self.title;
self.navigationItem.titleView = titleLabel;
[titleLabel release];

You may want to adjust the 10 value depending on your font size

Anthony Main
  • 6,039
  • 12
  • 64
  • 89
7

Swift 4 & 4.2 version:

 self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
steveSarsawa
  • 1,559
  • 2
  • 14
  • 31
Patricio Bravo
  • 406
  • 6
  • 8
6

It's recommended to set self.title as this is used while pushing child navbars or showing title on tabbars.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // create and customize title view
        self.title = NSLocalizedString(@"My Custom Title", @"");
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.text = self.title;
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor whiteColor];
        [titleLabel sizeToFit];
        self.navigationItem.titleView = titleLabel;
        [titleLabel release];
    }
}
Ramesh
  • 189
  • 1
  • 2
6

This is a pretty old thread but I think of providing answer for setting Color, Size and Vertical Position of Navigation Bar Title for iOS 7 and above

For Color and Size

 NSDictionary *titleAttributes =@{
                                NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                NSForegroundColorAttributeName : [UIColor whiteColor]
                                };

For Vertical Position

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];

Set Title and assign the attributes dictionary

[[self navigationItem] setTitle:@"CLUBHOUSE"];
self.navigationController.navigationBar.titleTextAttributes = titleAttributes;
Abdullah Saeed
  • 3,065
  • 1
  • 15
  • 27
6

I ran into the problem with my nav buttons throwing the text out of center (when you only have one button). To fix that I just changed my frame size like so:

CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
coryjacobsen
  • 998
  • 2
  • 9
  • 10
6

I've customized the navigationBar's background image and left button item, and the gray title not fit the background. Then I use:

[self.navigationBar setTintColor:[UIColor darkGrayColor]];

to change the tint color to gray. And the title is white now! That's what I want.

Hope to help also :)

Shiny
  • 583
  • 4
  • 16
  • Nice but that only works for changing the text to white. Even tinting the navBar with [UIColor whiteColor] changes the text color to white. – cschuff Dec 11 '11 at 13:14
5

This works for me in Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
zumzum
  • 17,984
  • 26
  • 111
  • 172
  • Pretty close but the thing is your way will overwrite all possible attributes already on the title. In my case that was the font. The code I ended up with was `navigationController?.navigationBar.titleTextAttributes = { if let currentAttributes = navigationController?.navigationBar.titleTextAttributes { var newAttributes = currentAttributes newAttributes[NSForegroundColorAttributeName] = navigationTintColor return newAttributes } else { return [NSForegroundColorAttributeName: navigationTintColor]}}()` – Matic Oblak Sep 18 '17 at 08:28
  • Works well. The same for Obj-C: `self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : UIColor.redColor};` – Mike Keskinov Jan 18 '18 at 18:30
4
self.navigationItem.title=@"Extras";
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
Kuldeep
  • 4,466
  • 8
  • 32
  • 59
Paresh Hirpara
  • 487
  • 3
  • 10
4

Use like this for Orientation support

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];

UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];
Kuldeep
  • 4,466
  • 8
  • 32
  • 59
Nikesh K
  • 621
  • 6
  • 10
3

I do believe proper way to set the colour of UINavigationBar is:

NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;

Code above is written is subclass on UINavigationBar, obviously works without subclassing as well.

Kuldeep
  • 4,466
  • 8
  • 32
  • 59
stringCode
  • 2,274
  • 1
  • 23
  • 32
  • Correct, but iOS 5 only. It's been long enough since iOS 5's release that it's a good solution. And since we're in iOS 5 world, it's worth noting that one can use `[UINavigationBar appearance]` and set title text attributes there (considering the trickery involved in subclassing `UINavigationBar`, a preferable solution). – Ivan Vučica Jul 17 '12 at 12:29
  • @stringCode. Can you initialize above code without " self.navigationController.navigationBar.titleTextAttributes = attributes; " ? – Gajendra K Chauhan Jun 14 '13 at 05:14
3

An update to Alex R. R.'s post using the new iOS 7 text attributes and modern objective c for less noise:

NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowColor = [UIColor blackColor];
titleShadow.shadowOffset = CGSizeMake(-1, 0);
NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                            NSShadowAttributeName:titleShadow};

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
phatblat
  • 3,804
  • 3
  • 33
  • 31
3

to set font size of title i have used following conditions.. maybe helpfull to anybody

if ([currentTitle length]>24) msize = 10.0f;
    else if ([currentTitle length]>16) msize = 14.0f;
    else if ([currentTitle length]>12) msize = 18.0f;
Shefali Soni
  • 249
  • 2
  • 2
2

After encountering the same problem (as others) of the label that moves when we insert a button in the navBar (in my case i have a spinner that i replace with a button when the date is loaded), the above solutions didn't work for me, so here is what worked and kept the label at the same place all the time:

- (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
    //CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
   CGRect frame = CGRectMake(0, 0, 180, 44);
    UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];



    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor yellowColor];
    self.navigationItem.titleView = label;
    label.text = NSLocalizedString(@"Latest Questions", @"");
    [label sizeToFit];
}

return self;
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
john
  • 535
  • 7
  • 16
2

This is one of those things that are missing. Your best bet is to create your own custom Navigation Bar, add a text box, and manipulate the color that way.

David McGraw
  • 5,157
  • 7
  • 36
  • 36
  • I'm following your idea :) which method should I override to start playing with the title? Sorry, I'm really a n00b :( – Sr.Richie Nov 09 '11 at 19:55
1

Can use this method in appdelegate file and can use at every view

+(UILabel *) navigationTitleLable:(NSString *)title
{
CGRect frame = CGRectMake(0, 0, 165, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = NAVIGATION_TITLE_LABLE_SIZE;
label.shadowColor = [UIColor whiteColor];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeTailTruncation;    
label.textAlignment = UITextAlignmentCenter;
[label setShadowOffset:CGSizeMake(0,1)]; 
label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];

//label.text = NSLocalizedString(title, @"");

return label;
}
sinh99
  • 3,909
  • 32
  • 32
1

titleTextAttributes Display attributes for the bar’s title text.

@property(nonatomic, copy) NSDictionary *titleTextAttributes Discussion You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the text attribute keys described in NSString UIKit Additions Reference.

Availability Available in iOS 5.0 and later. Declared In UINavigationBar.h

dip
  • 129
  • 1
  • 4
1

You should call [label sizeToFit]; after setting the text to prevent strange offsets when the label is automatically repositioned in the title view when other buttons occupy the nav bar.

George
  • 2,187
  • 2
  • 17
  • 11
0

In order to make Erik B's great solution more useable across the different UIVIewCOntrollers of your app I recommend adding a category for UIViewController and declare his setTitle:title method inside. Like this you will get the title color change on all view controllers without the need of duplication.

One thing to note though is that you do not need [super setTItle:tilte]; in Erik's code and that you will need to explicitly call self.title = @"my new title" in your view controllers for this method to be called

@implementation UIViewController (CustomeTitleColor)

- (void)setTitle:(NSString *)title
{
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];

        titleView.textColor = [UIColor blueColor]; // Change to desired color

        self.navigationItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = title;
    [titleView sizeToFit];
}

@end

Abolfoooud
  • 2,663
  • 2
  • 27
  • 27
0

I am using below code for the iOS 9 and its working fine for me. I have also use shadow color for the title.

self.navigationItem.title = @"MY NAV TITLE";
self.navigationController.navigationBar.barTintColor = [UIColor redColor];
self.navigationController.navigationBar.translucent = NO;
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.8];
shadow.shadowOffset = CGSizeMake(0, 1);
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                       [UIColor colorWithRed:245.0/255.0 green:245.0/255.0 blue:245.0/255.0 alpha:1.0], NSForegroundColorAttributeName,
                                                       shadow, NSShadowAttributeName,
                                                       [UIFont fontWithName:@"HelveticaNeue-Light" size:21.0], NSFontAttributeName, nil]];

May this help you.

Thanks

Ashu
  • 3,373
  • 38
  • 34