Swift:屏幕旋转(Device Orientation)

最近在项目中,遇到了大多数界面均为竖屏,但是有几个界面需要支持横屏的情况,在此记录一下如何实现(支持某个页面指定屏幕方向)。

1.设置app支持的方向

设置app仅支持竖屏 TARGETS->Genreal->Deployment Info->Device Orentation

image.png

2. 设置View controller-based status bar appearance

在info.plist文件中 添加View controller-based status bar appearance字段,值设为YES

YES:代表控制器对状态栏设置的优先级高于application
NO:代表application为准,控制器设置状态栏prefersStatusBarHidden是无效的的根本不会被调用

3. 通过AppDelegate实现

  • 声明屏幕支持的方向私有属性orientation
private var orientation: UIInterfaceOrientationMask = UIInterfaceOrientationMask.portrait
  • 我这里封装了一个public方法用来实现更改屏幕支持的方向
    /// 设置屏幕是否允许旋转
    /// - Parameters:
    ///   - allowRoation: 是否允许旋转
    ///   - orientation: 旋转方向
    public func setOrientaition(allowRoation: Bool, orientation: UIInterfaceOrientationMask) {
        self.orientation = orientation
        if allowRoation == false {
            self.orientation = .portrait
            // 设置为竖屏时强制旋转屏幕
            UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
        } else {
            switch orientation {
            case .landscapeLeft:
                // 设置为左横屏时强制旋转屏幕
                UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
                break
            case.landscapeRight:
                // 设置为右横屏时强制旋转屏幕
                UIDevice.current.setValue(UIDeviceOrientation.landscapeRight.rawValue, forKey: "orientation")
                break
            default:
                break
            }
        }
    }

如果不需要设置屏幕强制,可以根据需求对方法进行自定义。。。

一定要实现下边的方法!!!

//控制屏幕支持的方向
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        
        return self.orientation
    }

4.调用

在需要支持横屏的页面中的viewWillAppear中设置一下

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)    
        // 允许全屏
        wlAppDelegate?.setOrientaition(allowRoation: true, orientation: .allButUpsideDown)
    }

退出需要支持横屏的页面时,需要调用下viewDidAppear方法

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        wlAppDelegate?.setOrientaition(allowRoation: false, orientation: .portraitUpsideDown)
    }

为了便于在项目中快捷的调用AppDelegate,声明了一个全局变量。

let wlAppDelegate = UIApplication.shared.delegate as? AppDelegate
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 屏幕旋转 认知 期望达到的目的 如何让App支持屏幕旋转 如何让App屏幕旋转 如何保证屏幕旋转后布局不会乱 总结...
    超C阅读 657评论 0 0
  • 原文:https://www.jianshu.com/p/e2bbc312aac2 一 . 需求 APP中需要支持...
    Flora_HAHA阅读 4,684评论 0 8
  • 近期项目中需要对部分页面进行可旋转的控制,本篇文章算是对开发过程的一个总结。为何这么简单的东西要总结?还不是一直没...
    猴子的饼干阅读 715评论 0 0
  • 一. 需求 APP中需要支持横屏和竖屏,并在不同的页面 可支持的屏幕旋转方向不一致 整体竖屏,部分强制横屏 整体横...
    _skye阅读 7,541评论 4 10
  • 1、UIDeviceOrientation 设备的物理方向 简介UIDeviceOrientation即我们手持的...
    MrJ的杂货铺阅读 27,943评论 8 75