set the alignment of title of navigation bar

11,211

Solution 1

You don't have to use UILabel. You can directly use this code:

[self.navigationItem setTitle:@"Your Title"];

and you're good to go! This code will automatically lay its self to the center of the navigation bar.

Or if you actually have an instance of UINavigationController, use:

[self setTitle:@"Your Title"];

Solution 2

You need to set self.title = "" in the viewWillDisappear method in the previous viewcontroller.

Eg. ViewControllerB is opening from ViewControllerA then set self.title = "" in ViewControllerA's "viewWillDisappear" method

Share:
11,211
user1268938
Author by

user1268938

Updated on June 04, 2022

Comments

  • user1268938
    user1268938 almost 2 years

    I'm trying to align the title of the navigation bar to the center in my app but it seems the title is staying on the right side (please find the screen shot). I'm using the code below:

    -(void)viewDidLoad {
        UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStylePlain target:self action:@selector(goToHomePage:)];
        [self.navigationController.navigationItem.rightBarButtonItem setTarget:self];
        self.navigationItem.rightBarButtonItem = addButton;
        [addButton release];
    }
    

    in viewWillAppear() as below

    [self.navigationItem setTitle:offertitle];
    

    and tried this too

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 120, 40)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:14.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentLeft;
    label.textColor =[UIColor whiteColor];
    label.text=offertit;
    self.navigationItem.titleView = label;
    

    the title displays center aligned title when I hide the back button. Is there any method to set the appearance attributes of back button?

    image link here

    Can anyone guide me where i may have gone wrong.