SwiftUI导航栏高度

问题描述 投票:0回答:1

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

navigationController?.navigationBar.frame.height

但无法为SwiftUI找到任何东西...

height swiftui navigationbar
1个回答
0
投票

基于此帖子(感谢Asperihttps://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)
            }
        }
    }
}

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

.background(NavBarAccessor { navBar in
      print(">> NavBar height: \(navBar.bounds.height)")
                // !! use as needed, in calculations, @State, etc.
 })
© www.soinside.com 2019 - 2024. All rights reserved.