Skip to content

Instantly share code, notes, and snippets.

@hirohitokato
Created April 28, 2020 02:02
Show Gist options
  • Save hirohitokato/7c8a7814b731fc5bb453617bea265756 to your computer and use it in GitHub Desktop.
Save hirohitokato/7c8a7814b731fc5bb453617bea265756 to your computer and use it in GitHub Desktop.
iPadでも画面の向きによってAutoLayoutを適用したいときのコード
/*
iPadは縦横どちらの向きでもUIUserInterfaceSizeClassが.regularなので、AutoLayoutのOrientationによる表示変更ができない。
以下のコードを必要なViewControllerに書いておくと`.regular × .compact`と判断するようになりiPhoneと同じルールでレイアウトできる。
*/
// MARK: - Trick for iPad device orientation
override public var traitCollection: UITraitCollection {
let device = UIDevice.current
let result: UITraitCollection
if device.userInterfaceIdiom == .pad {
// デバイスの向きに応じて.compactを織り交ぜた値を返す
let traits: [UITraitCollection]
if device.orientation.isPortrait {
traits = [UITraitCollection(horizontalSizeClass: .compact),
UITraitCollection(verticalSizeClass: .regular)]
} else {
traits = [UITraitCollection(horizontalSizeClass: .regular),
UITraitCollection(verticalSizeClass: .compact)]
}
result = UITraitCollection(traitsFrom:traits)
} else {
result = super.traitCollection
}
return result
}
@hirohitokato
Copy link
Author

@hirohitokato
Copy link
Author

hirohitokato commented May 2, 2020

残念ながらこの方法はNG。上記コードを実行すると、コンソールに

Class 〜ViewController overrides the -traitCollection getter, which is not supported.
If you're trying to override traits, you must use the appropriate API.

と出てくる。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment