简体   繁体   English

导航栏,标题,通过代码居中对齐

[英]navigationbar, title, center alignment through code

I have a number of of xibs where I manipulate the title of the navigation bar through code: 我有许多xib,可通过代码在其中操纵导航栏的标题:

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. 获取barButton的宽度,并将其从标签的宽度中减去。

You can determine your bar button's frame through this method: 您可以通过以下方法确定条形按钮的框架:

Get the width of a UIBarButtonItem 获取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. 通过在设置标题视图之前添加按钮,xcode会自动正确设置对齐方式。 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];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM