[iOS开发] Orientation 界面旋转,支持横竖屏,局部界面旋转

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()

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容