下記のコードのようにナビゲーションバーを隠すためsetNavigationBarHiddenを記述しているがUIHostingControllerを使用しているとナビゲーションバーが隠れない。
class ThirdViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let hc = UIHostingController(rootView: SwiftUIView())
self.addChild(hc)
self.view.addSubview(hc.view)
hc.didMove(toParent: self)
hc.view.translatesAutoresizingMaskIntoConstraints = false
hc.view.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
hc.view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
}
}
![](https://qiita-user-contents.imgix.net/https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F662300%2Fb18dccd7-e3b0-c0b3-06df-82d3887a2865.png?ixlib=rb-4.0.0&auto=format&gif-q=60&q=75&s=5f42478152015cbced83320d2387276a)
対応方法としては下記のようなUIHostingControllerのカスタムクラスを作成すれば良いらしい。
class UIHostingControllerToHideNaviBar<Content: View>: UIHostingController<Content> {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
}
}
修正版
class ThirdViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let hc = UIHostingControllerToHideNaviBar(rootView: SwiftUIView()) //←作ったやつに変更
self.addChild(hc)
self.view.addSubview(hc.view)
hc.didMove(toParent: self)
hc.view.translatesAutoresizingMaskIntoConstraints = false
hc.view.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
hc.view.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true
}
}
完