问题描述
我正在努力隐藏navigationBar
,如果根控制器不是SwiftUI UIHostingController
,则应该正确隐藏navigationController.isNavigationBarHidden = true
。
我尝试了以下操作:
-
在创建
viewDidLoad
后在viewWillAppear
和.navigationBarHidden(true)
处进行设置。 -
为
.navigationBarBackButtonHidden(true)
的{{1}}添加UIHostingController
和rootView
。
这可能是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进行了测试
修改了您的代码:
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 测试