我有许多 xib,我在其中通过代码操作导航栏的标题:
titleLabel.text = @"custom Title";
titleLabel.textAlignment = UITextAlignmentCenter;
self.navigationItem.titleView = titleLabel;
我遇到的问题是,在某些情况下,我在该栏中添加了一个右按钮或左按钮,或者两者都添加,并且每当我这样做时,文本对齐最终会有点偏离并且没有正确居中。我该如何解决?
获取 barButton 的宽度并将其从标签的宽度中减去。
您可以通过此方法确定条形按钮的框架:
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);
我找到了一种解决方法。
通过在设置标题视图之前添加按钮,xcode 会自动正确设置对齐方式。顺序很重要。
这对我有用
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];
}