SwiftUI 导航栏高度

yop*_*rst 4 height navigationbar swiftui

如何获取当前的 NavigationBar 高度?在 UIKit 我们可以得到

navigationController?.navigationBar.frame.height
Run Code Online (Sandbox Code Playgroud)

但找不到任何适用于 SwiftUI 的东西...

yop*_*rst 13

基于这篇文章(感谢Asperi):https : //stackoverflow.com/a/59972635/12299030

struct NavBarAccessor: UIViewControllerRepresentable {
    var callback: (UINavigationBar) -> Void
    private let proxyController = ViewController()

    func makeUIViewController(context: UIViewControllerRepresentableContext<NavBarAccessor>) ->
                              UIViewController {
        proxyController.callback = callback
        return proxyController
    }

    func updateUIViewController(_ uiViewController: UIViewController, context: UIViewControllerRepresentableContext<NavBarAccessor>) {
    }

    typealias UIViewControllerType = UIViewController

    private class ViewController: UIViewController {
        var callback: (UINavigationBar) -> Void = { _ in }

        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            if let navBar = self.navigationController {
                self.callback(navBar.navigationBar)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以从任何视图调用它:

.background(NavBarAccessor { navBar in
      print(">> NavBar height: \(navBar.bounds.height)")
                // !! use as needed, in calculations, @State, etc.
 })
Run Code Online (Sandbox Code Playgroud)