Swift 强制屏幕旋转,全屏显示,iOS 16 适配

AppDelegate 实现下面的代理方法,并且判断对应的旋转方向

    static var isPortrait = true
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return AppDelegate.isPortrait ? .portrait : .landscapeLeft
    }

需要旋转的 controller 重写下面两个属性,例子中是强制向左旋转

class XXViewController: UIViewController {
    override var shouldAutorotate: Bool {
        true
    }

    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        .landscapeLeft
    }
}

iOS 16 之前的版本,需要手动调用 setOrientation 方法。

向左旋转

        AppDelegate.isPortrait = false
        if #unavailable(iOS 16) {
            let value = UIInterfaceOrientation.landscapeLeft.rawValue
            if UIDevice.current.responds(to: #selector(setValue(_:forKey:))) {
                // 及时更新旋转的方向,如果不更新,可能造成旋转失败
                _ = (UIApplication.shared.delegate as? AppDelegate)?.application(UIApplication.shared, supportedInterfaceOrientationsFor: view.window)
                UIDevice.current.setValue(value, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }
        }
        
        let vc = XXViewController()
        navigationController?.pushViewController(vc, animated: true)

还原旋转方向

        AppDelegate.isPortrait = true
        if #unavailable(iOS 16) {
            let value = UIInterfaceOrientation.portrait.rawValue
            if UIDevice.current.responds(to: #selector(setValue(_:forKey:))) {
                // 及时更新旋转的方向,如果不更新,可能造成旋转失败
                _ = (UIApplication.shared.delegate as? AppDelegate)?.application(UIApplication.shared, supportedInterfaceOrientationsFor: view.window)
                UIDevice.current.setValue(value, forKey: "orientation")
                UIViewController.attemptRotationToDeviceOrientation()
            }
        }
        navigationController?.popViewController()
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容