如何在swift中检查设备方向是左侧还是右侧?

if UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation) { print("landscape") } if UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation){ print("portrait") } 

如何检查它的横向是左还是右?

你可以做点什么,

 if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft{ } else if UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight{ } else if UIDevice.currentDevice().orientation == UIDeviceOrientation.UIDeviceOrientationPortraitUpsideDown{ } else if UIDevice.currentDevice().orientation == UIDeviceOrientation.UIDeviceOrientationPortrait{ } 

SWIFT 3

 if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft { } else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight { } else if UIDevice.current.orientation == UIDeviceOrientation.portrait { } else if UIDevice.current.orientation == UIDeviceOrientation.portraitUpsideDown { } 

这适用于Swift 3和4

 switch UIApplication.shared.statusBarOrientation { case .portrait: //do something break case .portraitUpsideDown: //do something break case .landscapeLeft: //do something break case .landscapeRight: //do something break case .unknown: //default break } 

有一件事会破坏所有这些答案 – 这是iOS9 iPad的多任务处理。

在iOS 9上,iPad应用程序默认选择iPad多任务处理。 这意味着它必须始终采用所有方向。 由于您没有选择退出iPad多任务处理,因此运行时假定您始终采用所有方向 – 因此它不需要费心询问您允许的方向,因为它已经知道答案(所有这些方向) )。

要为UICollectionView做正确的单元格大小,我接下来做:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if UIDevice.current.userInterfaceIdiom == .phone { return CGSize(width: collectionView.frame.size.width, height: 120) } else { var width:CGFloat = 0 let height = 250 // because of iOS9 and iPad multitasking if (UIApplication.shared.statusBarOrientation.rawValue <= UIInterfaceOrientation.portraitUpsideDown.rawValue) { width = (collectionView.frame.size.width - 3) / 3 } else { width = (collectionView.frame.size.width - 4) / 4 } return CGSize(width: Int(width), height: Int(height)) } } 

和内部viewWillTransition下一个:

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if let layout = self.collectionViewLayout as? UICollectionViewFlowLayout { layout.invalidateLayout() } } 

因为它比没有它更快。

UIDeviceOrientation将返回一个值:

  enum UIDeviceOrientation : Int { case Unknown case Portrait case PortraitUpsideDown case LandscapeLeft case LandscapeRight case FaceUp case FaceDown }