Adding custom view into NavigationBar not working?

六月ゝ 毕业季﹏ 提交于 2021-01-07 01:16:29

问题


I am trying to add custom view to NavigationBar and result not working correct.

 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 )
            ])
        }

        
       
    }

See the difference in notch device this:


回答1:


I have to make a change in your code, now it's work on all devices even iPhone 12 mini as shown in the image. 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)!),
            ])
        }
    }


来源:https://stackoverflow.com/questions/65103209/adding-custom-view-into-navigationbar-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!