下記のコードのようにナビゲーションバーを隠すため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
}
}
対応方法としては下記のような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
}
}
完