11
10

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.

StoryboardのSize ClassでiPadも縦横のレイアウトを切り替える

Last updated at Posted at 2016-08-23

StoryboardのSize ClassでiPhoneの縦横のレイアウトを切り替えたい場合、Any/Anyで共通のレイアウト作って、Any/Compact横用にレイアウトを作ったりします。
が、これをiPadで動作させると、縦でも横でも共通レイアウトになってしまいます。
Size ClassではiPadの縦と横のレイアウトを分ける設定はないようです。
iPhoneとiPadで同じように縦横でレイアウトを分けたい場合、これではちょっと不都合です。

これを解決するには以下の手順を行うとうまくようです。

  1. レイアウトを分けたいViewControllerを適当なViewControllerのChildViewControllerにします。
  2. ParentViewControllerの方でUIViewController#overrideTraitCollectionForChildViewController をoverrideし、画面の向きに応じた UITraitCollection を返してあげます。
override func overrideTraitCollection(forChildViewController childViewController: UIViewController) -> UITraitCollection? { {
        let any = UITraitCollection(verticalSizeClass: .unspecified)
        let compact = UITraitCollection(verticalSizeClass: .compact)
        
        // landscape
        if self.view.frame.width > self.view.frame.height {
            return UITraitCollection(traitsFrom: [any, compact])
        }
        
        // portrait
        return UITraitCollection(traitsFrom: [any, any])
    }

今回、例として以下の様にピンクのビューを縦の時は左上、横の時は右下になるように配置してみました。

   

で、iPadで起動して縦横回転させてみると
rotate.gif
ちゃんと縦横で切り替わりました。

ただ、ChildViewControllerにしないとダメなのがちょっと微妙ですね。
アップル的にはiPadは縦と横でレイアウトを分けてほしくないんでしょうか?

参考

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?