【问题标题】:UINavigationBar custom title positionUINavigationBar 自定义标题位置
【发布时间】:2011-05-13 13:19:26
【问题描述】:

我有一个自定义的 UINavigationBar(不同的大小、背景等),它在自定义标题视图中。我使用这段代码来实现这一点:

UIView * mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    mainView.backgroundColor = [UIColor yellowColor];

    UINavigationBar *navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0,0,kScreenWidth,80)];
    navBar.autoresizingMask = UIViewAutoresizingFlexibleWidth;

    UINavigationItem *currentItem = [[UINavigationItem alloc] init];
    UILabel *label = [[UILabel alloc] init];
    label.font = [UIFont fontWithName:@"Helvetica-Bold" size: 30.0];
    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setText:self.title];
    [label sizeToFit];
    [currentItem setTitleView:label];
    [label release];

    [navBar pushNavigationItem:currentItem animated:NO];
    [currentItem release];

    [mainView addSubview:navBar];
    [navBar release];    

    self.view = mainView;
[mainView release];

但是,我现在的问题是,即使正确添加了自定义标题视图,它也不会与导航栏垂直居中。我错过了什么?

谢谢!

【问题讨论】:

  • 为了……不要对屏幕尺寸进行硬编码,Apple 自 iPhone SDK 首次发布以来一直在宣传这一点。使用[UIScreen mainScreen].applicationFrame,它将适用于 iPhone/iPad 或任何未来的设备。在通话或网络共享时有或没有更大的状态栏。
  • 感谢 PeyloW,从现在开始会牢记这一点!
  • 不要使用 UIScreen 的框架,当您的应用在 iOS 9 上处于分屏模式时,它会给您错误的大小。请改用窗口的框架。

标签: iphone objective-c cocoa-touch


【解决方案1】:

您可以在 iOS 5 中使用setTitleVerticalPositionAdjustment:forBarMetrics: 更改标题位置,它适用于普通标题,例如:

CGFloat verticalOffset = -4;
[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:verticalOffset forBarMetrics:UIBarMetricsDefault];

【讨论】:

  • 不幸的是,有时需要从中心水平偏移标题才能看起来正确。例如,在 UINavigationBar 中,您可能有一个按钮,左侧显示“取消”,右侧显示“完成”。即使标题在栏中居中,但它不在按钮之间居中并且看起来不正确。因此,在某些情况下,使用 UINavigationBarItem.titleView 可能是可行的方法。
【解决方案2】:

当标准UINavigationBar 有 44 分时,您创建的 UINavigationBar 高度为 80 分。它可能将其定位在一个 44 分的中心...

您可以尝试制作一个高度为 80 pts 的UIView,并在其中添加居中的UILabel。 (未测试,只是猜测)

【讨论】:

  • 我也有同样的感觉,但我将UINavigationBar 做得更大,并且标题仍然保持其位置(UINavigationBar 底线上方的几个点)。基本上,无论UINavigationBar 有多大,标题都会比它的底线高几分。将立即尝试 UIView 并报告。
  • 添加更大的 UIView 可以工作(如果我将其设置为与 UINavigationBar 相同的大小)谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-23
  • 2013-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多