Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Navigation Controller title not centered

I have a navigation controller with a custom back button on the left. I do this programmatically so this is not an auto-layout issue. My problem is that the navigation controller title is not centered, it is going off the right side of the screen. I remember seeing a fix for this awhile back dealing with setting some type of fixed space as the right bar button item, but I cannot seem to find anything similar to this now.

Could someone tell me how to set the navigation controller title to centered and if the title is too big for its space, set nav bar title to fix its font size to fit the width of title space. This all needs to be done programmatically, thanks!

like image 793
MSU_Bulldog Avatar asked Sep 09 '15 14:09

MSU_Bulldog


2 Answers

In navigation controller, by default, the view controller A that pushes current view controller B. The title of A will show up in backBarButton in view controller B.

The navigation controller title not centered is also because the previous view controller title is too long.

To counter that, use this in viewWillAppear of view controller A:

self.navigationItem.backBarButtonItem= UIBarButtonItem(title: "", 
    style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.navigationItem.backBarButtonItem!.title = ""`
like image 88
Yongxiang Ruan Avatar answered Nov 14 '22 17:11

Yongxiang Ruan


You have to add custom view in the navigation

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(10, 0, 150, 44)];

    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 165,370, 25)];
    titleLabel.text=@"Home";
    titleLabel.textColor=[UIColor whiteColor];
    [view addSubview:titleLabel];    
    [self.navigationController.navigationBar addSubview:view];
like image 3
Nikunj Avatar answered Nov 14 '22 17:11

Nikunj