问题描述
我正在努力隐藏 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
,在viewDidLoad
和viewWillAppear
.
为 UIHostingController
的 rootView.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 的导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!