1. 在info.plist或者Target/General里配置要支持的方向
2. 在AppDelegate.m中,重新以下方法,返回要支持的方向
```
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return AppPreference.supportedInterfaceOrientations
}
// 可设置默认支持的方向
class AppPreference: NSObject {
static var supportedInterfaceOrientations : UIInterfaceOrientationMask = .portrait
}
```
3. 在需要旋转方向的界面viewWillAppear和viewWillDisappear,修改AppPreference.supportedInterfaceOrientations值
```
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
AppPreference.supportedInterfaceOrientations = .allButUpsideDown
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
AppPreference.supportedInterfaceOrientations = .portrait
}
```
4. 在支持旋转的界面,重写viewWillTransition ,对子view重新布局,例如CollectionView/scrollView重新定位,如果已经使用自动布局,则什么都不用做
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
}
5. 强制旋转
强制旋转依赖UIDevice.orientation,用KVC注入新值(api没有提供setter),可在步骤4记录当前device.orientation,在强制旋转时可以toggle
```
UIDevice.current.setValue(displayingOrientation.rawValue, forKey: "orientation")
UIViewController.attemptRotationToDeviceOrientation()
```