8
9

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.

shouldAutorotate() が呼ばれない

Last updated at Posted at 2016-08-04

#問題
[UITabViewController]->[UINavigationController]->[UIViewController]という構造になっているとき、UIViewControllerを継承したViewの中で

override var shouldAutorotate: Bool{
    return false
}

を書いても、画面が回転してしまう。
UIViewControllerが回っていなくても、その下にあるUITabViewControllerとUINavigationControllerが回ってしまっているからだ。
#解決方法
これをどこかに追記する。ちなみにshouldAutorotate以外にも個人的に書いておいたほうがいいと思ってるものも入ってる。

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

extension UITabBarController{
    open override var shouldAutorotate: Bool {
        guard let viewCtrls = self.viewControllers else{return true}
        return viewCtrls[selectedIndex].shouldAutorotate
    }
    open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        guard let viewCtrls = self.viewControllers else{return .all}
        return viewCtrls[selectedIndex].supportedInterfaceOrientations
    }
}

#コメント
UINavigationControllerのextensionを追記するのはどのサイトでも出てきたけど、UITabBarControllerがあるのが盲点だった。ちょっと書き方が複雑だったように思う。

上の書き方はSwift3.0だけど、Swift2系なら

open override var なになに: なになに{

public override func なになに() -> なになに{

に書き換えればいい。

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?