如何获取当前NavigationBar的高度?在UIKit中,我们可以得到
navigationController?.navigationBar.frame.height
但无法为SwiftUI找到任何东西...
基于此帖子(感谢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) } } } }
然后我们可以从任何视图调用此:
.background(NavBarAccessor { navBar in
print(">> NavBar height: \(navBar.bounds.height)")
// !! use as needed, in calculations, @State, etc.
})