您的自定义栏视图的布局如下:
[nav.topAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.topAnchor];
任何受限于 view.safeAreaLayoutGuide.topAnchor 的东西都将位于 statusBar + navigationBar 下方,因为那是安全区域。如果它受限于 safeAreaLayoutGuide.bottomAnchor,那么它将位于所有 tabBars 或底部栏之上,以便 iPhone X 用户可以向上滑动而不触及您的视图..
但是,任何受限于 view.topAnchor 的东西都将受限于视图的顶部(IE:屏幕)。
因此,将您的自定义视图限制在控制器视图的顶部。然后在 中viewDidLayoutSubviews
,添加safeAreaInsets.top
到高度。这将允许您的视图触摸屏幕顶部,但高/大到足以延伸到导航栏下方。您将需要调整视图的内容以在相同的插图顶部进一步向下布局。
//
// ViewController.swift
// SONav
//
// Created by Brandon Anthony on 2017-11-17.
// Copyright © 2017 SO. All rights reserved.
//
import UIKit
class CustomNav : UINavigationBar {
var desiredHeight: CGFloat = 88.0
override init(frame: CGRect) {
super.init(frame: frame)
desiredHeight = frame.size.height
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var size = super.sizeThatFits(size)
size.height = desiredHeight
return size
}
override var frame: CGRect {
get {
return super.frame
}
set {
var frm = newValue
frm.size.height = desiredHeight
super.frame = frm
}
}
override func layoutSubviews() {
super.layoutSubviews()
for subview in self.subviews {
if NSStringFromClass(type(of: subview)).contains("Background") {
subview.frame.size.height = 0
}
else if NSStringFromClass(type(of: subview)).contains("ContentView") {
subview.frame.origin.y = 0
}
}
}
}
class CustomNavigationController : UINavigationController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
self.setNeedsStatusBarAppearanceUpdate()
}
}
class ViewController: UIViewController {
var customNav: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//Navigation Bar Setup
self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController?.navigationBar.isTranslucent = true
self.navigationController?.view.backgroundColor = UIColor.clear
self.navigationController?.navigationBar.backgroundColor = UIColor.clear
self.navigationController?.navigationBar.shadowImage = nil
self.view.backgroundColor = UIColor.white
self.customNav = CustomNav(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 100))
self.customNav.backgroundColor = UIColor.blue
self.view.addSubview(self.customNav!)
NSLayoutConstraint.activate([
self.customNav.leftAnchor.constraint(equalTo: self.view.leftAnchor),
self.customNav.rightAnchor.constraint(equalTo: self.view.rightAnchor),
self.customNav.topAnchor.constraint(equalTo: self.view.topAnchor),
self.customNav.heightAnchor.constraint(equalToConstant: 100.0)
])
self.customNav.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}