user141146
user141146

Reputation: 3315

Setting font and font-size of title bar text in a UITableViewController

I have a simple navigation based application for the iphone/objective-c

within various UIViewControllers that are pushed into view, I can set the text in the title bar using something like

self.title = @"blah blah blah"

Is there a way to control the font and font-size of the title in the title bar text?

thanks!

Upvotes: 10

Views: 17088

Answers (4)

zirinisp
zirinisp

Reputation: 10291

IF you want this to work both on iphone and ipad, and also want to get the title centered then use the following code.

 - (void)viewDidLoad
{
    [super viewDidLoad];

    UILabel* label=[[UILabel alloc] initWithFrame:CGRectMake(0,0, self.navigationItem.titleView.frame.size.width, 40)];
    label.text=self.navigationItem.title;
    label.textColor=[UIColor whiteColor];
    label.backgroundColor =[UIColor clearColor];
    label.adjustsFontSizeToFitWidth=YES;
    label.font = [AppHelper titleFont];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView=label;
}

Upvotes: 4

Jonathan Moffatt
Jonathan Moffatt

Reputation: 13457

You may want to emboss the label so it doesn't look fuzzy and flat:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect frame = CGRectMake(0, 0, 400, 44);
    UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:18.0];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor whiteColor];
    label.text = self.navigationItem.title;
    // emboss so that the label looks OK
    [label setShadowColor:[UIColor darkGrayColor]];
    [label setShadowOffset:CGSizeMake(0, -0.5)];
    self.navigationItem.titleView = label;
}

Upvotes: 5

roocell
roocell

Reputation: 2449

the proper way to resize the title text of a navcontroller is to set the titleView property of the navigationItem

like this (in viewDidLoad)

   UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 300, 40)];
        tlabel.text=self.navigationItem.title;
    tlabel.textColor=[UIColor whiteColor];
    tlabel.backgroundColor =[UIColor clearColor];
    tlabel.adjustsFontSizeToFitWidth=YES;
    self.navigationItem.titleView=tlabel;

Upvotes: 17

Ramin
Ramin

Reputation: 13433

You can assign any UIView to a navcontroller's title area.

Create a UILabel and set its font and size anyway you want, then assign it to the UIViewController's navigationItem.titleView property. Make sure the UILabel's backgroundColor is set to clearColor.

This only works on the top-level nav-view. As the user drills down into the view controller hierarchy and the "back" button is shown the alternate titleView is ignored and the regular text label is shown.

Upvotes: 3

Related Questions