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?
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
ie
NSInteger barButtonWidth = //determined through method above ^^^^^
titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.size.width-barButtonWidth, titleLabel.size.height);
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.
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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.