Created
April 28, 2020 02:02
-
-
Save hirohitokato/7c8a7814b731fc5bb453617bea265756 to your computer and use it in GitHub Desktop.
iPadでも画面の向きによってAutoLayoutを適用したいときのコード
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
残念ながらこの方法はNG。上記コードを実行すると、コンソールに
と出てくる。