将自定义视图添加到 NavigationBar 不起作用?

Adding custom view into NavigationBar not working?

我正在尝试向 NavigationBar 添加自定义视图,但结果无法正常工作。

 public let statusBarHeight: CGFloat = {
    var heightToReturn: CGFloat = 0.0
         for window in UIApplication.shared.windows {
             if let height = window.windowScene?.statusBarManager?.statusBarFrame.height, height > heightToReturn {
                 heightToReturn = height
             }
         }
    return heightToReturn
}()

 override func viewDidLoad() {
        super.viewDidLoad()
//        self.navigationController?.navigationBar.isHidden = true
        // Do any additional setup after loading the view.
       let barView = UIView(frame: CGRect.zero)
        barView.backgroundColor = .purple
        barView.translatesAutoresizingMaskIntoConstraints = false
        
        if let navBarSize = self.navigationController?.navigationBar.frame.size {
//            barView.frame.size = CGSize(width: navBarSize.width, height: navBarSize.height + statusBarHeight)
            self.navigationController?.navigationBar.subviews.first?.insertSubview(barView, at: 0)
            NSLayoutConstraint.activate([
                barView.leadingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.leadingAnchor)!),
                barView.trailingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.trailingAnchor)!),
                barView.heightAnchor.constraint(equalToConstant: navBarSize.height + statusBarHeight )
            ])
        }

        
       
    }

看看刘海屏的区别:

我必须更改您的代码,现在它可以在所有设备上运行,甚至 iPhone 12 mini,如图所示。 check image

override func viewDidLoad() {
        super.viewDidLoad()
        let barView = UIView(frame: CGRect.zero)
        barView.backgroundColor = .purple
        barView.translatesAutoresizingMaskIntoConstraints = false
        if (self.navigationController?.navigationBar.frame.size) != nil {
            self.navigationController?.navigationBar.subviews.first?.insertSubview(barView, at: 0)
            NSLayoutConstraint.activate([
                barView.leadingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.leadingAnchor)!),
                barView.trailingAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.trailingAnchor)!),
                barView.topAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.topAnchor)!),
                barView.bottomAnchor.constraint(equalTo: (self.navigationController?.navigationBar.subviews.first!.bottomAnchor)!),
            ])
        }
    }