1

我正在努力隐藏navigationBar,如果根控制器不是 SwiftUI ,它将被正确隐藏UIHostingController

我尝试了以下方法:

  • 创建后设置navigationController.isNavigationBarHidden = true,在viewDidLoadviewWillAppear

  • 为's添加.navigationBarHidden(true)和。.navigationBarBackButtonHidden(true)UIHostingControllerrootView

会不会是苹果的bug?我正在使用 Xcode 11.6。

我所有的尝试:

class LoginController: UINavigationController, ObservableObject
{
    static var newAccount: LoginController
    {
        let controller = LoginController()
        let view = LoginViewStep1()
            .navigationBarHidden(true)
            .navigationBarBackButtonHidden(true)
        controller.viewControllers = [UIHostingController(rootView: view)]
        controller.isNavigationBarHidden = true
        return controller
    }
    
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        
        self.isNavigationBarHidden = true
    }

    override func viewDidLoad()
    {
        super.viewDidLoad()

        self.isNavigationBarHidden = true
    }
}

struct LoginViewStep1: View
{
    // ...
    
    var body: some View
    {
        VStack {
            // ...
        }
        .navigationBarHidden(true)
        .navigationBarBackButtonHidden(true)
    }
}
4

2 回答 2

4

这是一个解决方案。使用 Xcode 11.4 / iOS 13.4 测试

演示

修改了您的代码:

class LoginController: UINavigationController, ObservableObject
{
    static var newAccount: LoginController
    {
        let controller = LoginController()
        let view = LoginViewStep1()
        controller.viewControllers = [UIHostingController(rootView: view)]

        // make it delayed, so view hierarchy become constructed !!!
        DispatchQueue.main.async {
            controller.isNavigationBarHidden = true
        }

        return controller
    }
}

struct LoginViewStep1: View
{
    var body: some View
    {
        VStack {
            Text("Hello World!")
        }
    }
}

测试部分SceneDelegate

if let windowScene = scene as? UIWindowScene {
    let window = UIWindow(windowScene: windowScene)

    window.rootViewController = LoginController.newAccount

    self.window = window
    window.makeKeyAndVisible()
}
于 2020-08-12T13:49:03.537 回答
1

替代解决方案是使用 UINavigationControllerDelegate:

func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
    // Required because pushing UIHostingController makes the navigationBar appear again
    isNavigationBarHidden = true
}

使用 iOS 14.5 - Xcode 12.5 测试

于 2021-04-23T19:07:48.453 回答