20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ViewControllerごとに画面の向きを固定する

Posted at

ViewControllerごとに画面の向きを固定するには、

  • shouldAutorotate
  • supportedInterfaceOrientations

をオーバーライドすればいい

MyViewController.swift
class MyViewController: UIViewController {
    ...
    // 画面を自動で回転させるか
    override var shouldAutorotate: Bool {
        get {
            return false
        }
    }
    
    // 画面の向きを指定
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        get {
            return .portrait
        }
    }
    ...
}

ただ、

  • UINavigationController
  • UITabBarController
  • UIPageViewController

なんかを使ってるとMyViewControllerに書いても動いてくれない
MyNavigationControllerを作ってもいいけれど、これだけのために用意するのは少々面倒なので、AppDelegateに以下を追加して対応

AppDelegate.swift
extension UINavigationController {
    open override var shouldAutorotate: Bool {
        guard let viewController = self.visibleViewController else { return true }
        return viewController.shouldAutorotate
    }
    
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        guard let viewController = self.visibleViewController else { return .all }
        return viewController.supportedInterfaceOrientations
    }
}

これで、各ViewControllerでオーバーライドした設定がちゃんと反映された

20
21
1

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
20
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?