LoginSignup
2
2

More than 1 year has passed since last update.

画面の一部でUIHostingControllerを使っているとNavigationBarを隠したいのに隠れない問題の対応方法

Posted at

下記のコードのようにナビゲーションバーを隠すため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
    }
}

そうすると隠れるようになった。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2