当根控制器是 UIHostingController 时隐藏 UINavigationController 的导航栏 [英] Hide UINavigationController's navigationBar when the root controller is a UIHostingController

查看:70
本文介绍了当根控制器是 UIHostingController 时隐藏 UINavigationController 的导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am struggling to hide the navigationBar, which would properly be hidden if the root controller wasn't a SwiftUI UIHostingController.

我尝试了以下方法:

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

UIHostingControllerrootView<添加 .navigationBarHidden(true).navigationBarBackButtonHidden(true)/代码>.

Adding both .navigationBarHidden(true) and .navigationBarBackButtonHidden(true) for the UIHostingController's rootView.

会不会是苹果的bug?我使用的是 Xcode 11.6.

Could it be an Apple bug? I am using 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 测试

Here is a solution. Tested with 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()
}

这篇关于当根控制器是 UIHostingController 时隐藏 UINavigationController 的导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆