デバイスが横向き左/右または上下逆の場合、回転して別のビュー コントローラーを表示するコードを取得しました。ただし、デバイスが上向きまたは下向きの向きの場合、横向きモードか縦向きモードかをどのように判断すればよいでしょうか。デバイスが上向きまたは下向きで横向きモードの場合のみ回転したいからです。
- (void)viewDidAppear:(BOOL)animated
{
UIDeviceOrientation orientation = [[UIDevice currentDevice]orientation];
NSLog(@"orientation %d", orientation);
if ((orientation == 2) || (orientation == 3) || (orientation == 4))
{
[self performSegueWithIdentifier:@"DisplayLandscapeView" sender:self];
isShowingLandscapeView = YES;
}
}
ベストアンサー1
このinterfaceOrientation
プロパティはiOS 8以降では非推奨です。ヘルパーメソッド
UIDeviceOrientationIsPortrait(orientation)
UIDeviceOrientationIsLandscape(orientation)
どちらも役に立ちません。方向が の場合に false を返すためです.faceUp
。
そこで私は次のように確認しました:
extension UIViewController {
var isPortrait: Bool {
let orientation = UIDevice.current.orientation
switch orientation {
case .portrait, .portraitUpsideDown:
return true
case .landscapeLeft, .landscapeRight:
return false
default: // unknown or faceUp or faceDown
guard let window = self.view.window else { return false }
return window.frame.size.width < window.frame.size.height
}
}
}
これは UIViewController 拡張機能内にあるため、他のすべてが失敗した場合は、画面の幅と高さの比較に戻ることができます。
window
現在の ViewController がコンテナーに埋め込まれている場合、グローバルな iPad の向きが反映されない可能性があるため、これを使用します。