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

你可能感兴趣的:(Swift 强制屏幕旋转,全屏显示,iOS 16 适配)