LoginSignup
1
2

More than 5 years have passed since last update.

UINavigationControllerを継承してるときの画面回転

Posted at

UIViewController側でshouldAutorotateとsupportedInterfaceOrientationsで画面回転しないように設定してるのに、画面回転がされてしまう! と焦ったので、メモ

 問題

  • UINavigationControllerを継承して独自のNavigationBarを作ってる
  • 特定の、UINavigationController内に配置されているUIViewControllerにて画面回転を防ぎたい
  • が、画面回転される。

UIViewController側


    // 画面の自動回転をさせない
    override var shouldAutorotate: Bool {
        get {
            return false
        }
    }

    // 画面をPortraitに指定する
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .portrait
        }
    }

対策

それぞれviewcontrollerから設定を取るようにすれば解決。


import UIKit

class NavigationController: UINavigationController {


    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        guard let vc = self.viewControllers.last else {
            return .all
        }
        return vc.supportedInterfaceOrientations
    }

    override var shouldAutorotate: Bool {
        guard let vc = self.viewControllers.last else {
            return true
        }
        return vc.shouldAutorotate
    }
1
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
1
2