0

I have a number of of xibs where I manipulate the title of the navigation bar through code:

titleLabel.text = @"custom Title";
titleLabel.textAlignment = UITextAlignmentCenter;
self.navigationItem.titleView = titleLabel;

The problem I have is that in some cases I add to that bar a right or left button, or both, and whenever I do that the text alignment ends up being a little bit off and not centered proerly. How can I fix that?

Kalamantina
  • 303
  • 4
  • 10

3 Answers3

1

Get the width of the barButton and subtract it from the label's width.

You can determine your bar button's frame through this method:

Get the width of a UIBarButtonItem

i.e.

NSInteger barButtonWidth = //determined through method above ^^^^^

titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.size.width-barButtonWidth, titleLabel.size.height); 
Community
  • 1
  • 1
Sarreph
  • 1,986
  • 2
  • 19
  • 41
0

I kind of found out a workaround it.

By adding the the buttons before setting the title view, xcode automatically sets the alignment properly. the order is important.

Kalamantina
  • 303
  • 4
  • 10
0

This worked for me

UILabel *labelNav;

- (void)viewDidLoad {
    [super viewDidLoad];
    labelNav=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 150, 20)];
    labelNav.font=[UIFont fontWithName:boldFont size:15];
    labelNav.textColor=barTintColor;
    labelNav.text=kBoostBusinessHoursScreenTitle;
    labelNav.textAlignment=NSTextAlignmentCenter;
    labelNav.center=self.navigationController.navigationBar.center;
    CGRect framelabel=labelNav.frame;
    framelabel.origin.y=12;
    labelNav.frame=framelabel;
    [self.navigationController.navigationBar addSubview:labelNav];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [labelNav removeFromSuperview];
}
Ravi Bihani
  • 471
  • 4
  • 5