导航栏标题对齐问题

时间:2014-11-13 06:55:09

标签: ios objective-c ios7 uinavigationbar

我已将自定义视图设置为导航栏titleView,当页面是第一个视图时,控制器标题在中心正确显示

Correct Image

但是当视图控制器从另一个视图控制器推出时,控制器标题将转移到右侧

Incorrect Image

代码:

-(void)setUpTwoLineNavigationTitle {
    CGFloat width = 0.95 * self.view.frame.size.width;
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 44)];
    contentView.backgroundColor = [UIColor clearColor];

    CGRect titleRect = contentView.frame;
    titleRect.origin.y = 4;
    titleRect.size.height = 20;

    UILabel *titleView = [[UILabel alloc] initWithFrame:titleRect];
    titleView.backgroundColor = [UIColor clearColor];
    titleView.font = [UIFont systemFontOfSize:14.0];
    titleView.textAlignment = NSTextAlignmentCenter;
    titleView.textColor = [UIColor blackColor];
    titleView.text = @"";
    [contentView addSubview:titleView];

    CGRect subTitleRect = contentView.frame;
    subTitleRect.origin.y = 24;
    subTitleRect.size.height = subTitleRect.size.height - 24;
    //CGRect subtitleFrame = CGRectMake(0, 24, 220, 44-24);
    UILabel *subtitleView = [[UILabel alloc] initWithFrame:subTitleRect];
    subtitleView.backgroundColor = [UIColor clearColor];
    subtitleView.font = [UIFont systemFontOfSize:11.0];
    subtitleView.textAlignment = NSTextAlignmentCenter;
    subtitleView.textColor = [UIColor blackColor];
    subtitleView.text = @"";
    [contentView addSubview:subtitleView];

    contentView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    self.navigationItem.titleView = contentView;
}

有人可以帮我纠正这个吗?

Github链接:https://github.com/iamabhiee/NavigationTitleDemo

1 个答案:

答案 0 :(得分:8)

这是一种解决方法,它可能很有用,我们的想法是使用UILabel作为titleView的{​​{1}}。这样您就不必手动计算和调整其框架,它将自动由系统居中。代码中的范围是硬编码的。

navigationItem