swift 屏幕旋转

竖直项目中遇到在某个页面支持横屏
第一步:
AppDelegate中设置一个变量标记是否要旋转
var allowRotation = false
设置支持方向

 func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        if self.allowRotation {
            return UIInterfaceOrientationMask.all
        }
        return UIInterfaceOrientationMask.portrait
    }

第二步:
要支持的横屏的vc
重写shouldAutorotate方法

 func shouldAutorotate() -> Bool {
        return false
    }

获取appDelegate 用来修改是否旋转变量

  let appDeleagte = UIApplication.shared.delegate as! AppDelegate

如果是进来vc不需要支持旋转,点击事件后才旋转
在需要横屏的事件中添加旋转代码

        appDeleagte.allowRotation = true
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")

在需要结束横屏的事件中添加旋转代码

        appDeleagte.allowRotation = false
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")

如果是进来vc就需要支持旋转则需要

 override func viewDidLoad() {
  appDeleagte.allowRotation = true
}
override func viewWillAppear(animated: Bool) {  
      let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
}

上面两种场景在页面消失的时候都要处理,设置为竖屏

override func viewWillDisappear(animated: Bool) {  
  appDeleagte.allowRotation = false
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
}  

如果需要旋转的时候做处理 可以通过进到UIViewController API 找到对应时机的代理方法

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容