以编程方式添加一个UINavigationBar,它确实覆盖了状态栏

我在View Controllers loadView手动添加UINavigationBar。

我正在使用制图( https://github.com/robb/Cartography )来布局使用自动布局的视图。

 self.edgesForExtendedLayout = UIRectEdge.None let navBar = UINavigationBar() navBar.delegate = self view.addSubview(navBar) constrain(navBar) { bar in bar.top == bar.superview!.top bar.centerX == bar.superview!.centerX bar.width == bar.superview!.width } 

代表方法:

 public func positionForBar(bar: UIBarPositioning) -> UIBarPosition { return .TopAttached } 

结果是小条,而不是状态栏下的扩展版。

如果要以编程方式添加导航栏,则需要注意edgesForExtendedLayout和任何条形定位API都不会相对于界面的布局指南。 由于您现在已经表明要管理此栏,因此系统无法强制它是否应位于状态栏下。 您需要做的是配置约束,使条形图始终相对于顶部布局指南定位。

所以对于初学者来说,请转到你的loadView方法:

 let bar = UINavigationBar() bar.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(bar) self.navBar = bar let topLayoutGuide = self.topLayoutGuide 

我们现在需要确保导航栏的底部相对于布局指南定位。 所以我们所做的就是说导航栏的底部= layoutGuides的顶部+ 44.其中44是导航栏的合适高度。 请记住,布局指南可以在您打电话时更改,因此始终使用布局指南并且永远不要硬编码状态栏高度非常重要。

使用制图的方法

 constrain(navBar) { bar in bar.top == bar.superview!.top bar.width == bar.superview!.width bar.bottom == topLayoutGuide.top + 44 } 

方法使用NSLayoutConstraints

 let navBarTopConstraint = NSLayoutConstraint(item: bar, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0) let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[bar]-0-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["bar":bar]) let navBarBottomConstraint = NSLayoutConstraint(item: bar, attribute: .Bottom, relatedBy: .Equal, toItem: topLayoutGuide, attribute: .Top, multiplier: 1, constant: 44) self.view.addConstraints([navBarTopConstraint,navBarBottomConstraint,horizontalConstraints])) 

瞧! 您现在有几行响应状态栏的自定义导航栏