当根控制器是UIHostingController时,隐藏UINavigationController的navigationBar

问题描述

我正在努力隐藏navigationBar,如果根控制器不是SwiftUI UIHostingController,则应该正确隐藏navigationController.isNavigationBarHidden = true

我尝试了以下操作:

  • 在创建viewDidLoad后在viewWillAppear.navigationBarHidden(true)处进行设置。

  • .navigationBarBackButtonHidden(true)的{​​{1}}添加UIHostingControllerrootView

这可能是Apple的错误吗?我正在使用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)
    }
}

解决方法

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

demo

修改了您的代码:

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()
}
,

替代解决方案是使用 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 测试

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...