SwiftUI隐藏UIKit的导航栏UINavigationController(rootViewController:_)

时间:2020-07-26 10:24:14

标签: swift swiftui uikit

我有一个SwiftUI视图:

struct Content View: View {
  var body: some View {
    Text("Content view")
  }
}

然后我使用了用UIKit创建的菜单。我的观点应该是UIViewControllerUINavigationController。为了显示我的swiftUI视图,我将视图设置在UINavigationController内:

let navigationController = UIHostingController(rootView: Content()).inNavigation()

// inNavigation()
extension UIViewController{
    func inNavigation() -> UIViewController {
        let vc = self
        let navigationController = UINavigationController(rootViewController: self)
        vc.navigationController?.navigationBar.isHidden = true
        vc.navigationController?.setNavigationBarHidden(true, animated: true)
        vc.navigationController?.isNavigationBarHidden = true
        vc.navigationController?.isToolbarHidden = true
        vc.navigationController?.setToolbarHidden(true, animated: true)
        vc.navigationController?.accessibilityFrame = .zero
        
        navigationController.navigationController?.navigationBar.isHidden = true
        navigationController.navigationController?.setNavigationBarHidden(true, animated: true)
        navigationController.navigationController?.isNavigationBarHidden = true
        navigationController.navigationController?.isToolbarHidden = true
        navigationController.navigationController?.setToolbarHidden(true, animated: true)
        navigationController.accessibilityFrame = .zero
        return navigationController
    }
}

我试图隐藏navigationBar。但它仍然显示:

enter image description here

1 个答案:

答案 0 :(得分:1)

UINavigationController应该处于视图层次结构中,这样才能生效。

这里是工作版本,假设您将其注入SceneDelegate中的窗口中(已通过Xcode 11.4 / iOS 13.4测试)

extension UIViewController{
    func inNavigation() -> UIViewController {
        let navigationController = UINavigationController(rootViewController: self)
        DispatchQueue.main.async {
            navigationController.isNavigationBarHidden = true
        }
        return navigationController
    }
}