【问题标题】:navigationbar, title, center alignment through code导航栏,标题,通过代码居中对齐
【发布时间】:2015-10-27 18:53:17
【问题描述】:

我有许多 xib,我通过代码操作导航栏的标题:

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

我遇到的问题是,在某些情况下,我在该栏中添加了一个右按钮或左按钮,或者两者都添加,每当我这样做时,文本对齐最终会有点偏离并且没有正确居中。我该如何解决?

【问题讨论】:

标签: ios xcode


【解决方案1】:

获取 barButton 的宽度并从标签的宽度中减去。

您可以通过此方法确定您的条形按钮的框架:

Get the width of a UIBarButtonItem

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

titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.size.width-barButtonWidth, titleLabel.size.height); 

【讨论】:

  • 这不行,标签仍然偏离中心。
  • 我没有进一步研究,愿意分享您的任何发现吗?
【解决方案2】:

我找到了一种解决方法。

通过在设置标题视图之前添加按钮,xcode 会自动正确设置对齐方式。顺序很重要。

【讨论】:

    【解决方案3】:

    这对我有用

    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];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-21
      • 1970-01-01
      • 2015-01-10
      • 2014-02-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2014-03-20
      相关资源
      最近更新 更多