iOS中如何设置手机横屏进入App首屏保持竖屏

在平时开发中,我们经常会忽略一个问题,就是当我们的App内有需要横屏的页面,而首页只支持竖屏,在plus的设备上,桌面是运行横屏的,此时进入App,首页布局会出错。在延伸一下这个问题,当我们开发一款支持iPad的App时,如何保证App在任何情况下进入首页都保持竖屏状态?

方法一、

我们可以这样设置首页的控制器:

    // 必须两个都是 .portrait才可以
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }

如果有UITabBarController,这样设置:

    // 必须两个都是 .portrait才可以
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return selectedViewController?.supportedInterfaceOrientations ?? .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }

如果有 UINavigationController,这样设置:

    // 必须两个都是 .portrait才可以保证首页一定是竖屏
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return topViewController?.supportedInterfaceOrientations ?? .portrait
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }

方法二、

设置一个全局的变量

var isAllowLandscape: Bool = false

在AppDelegate中设置:

    // 控制整个App所允许旋转的方向
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return isAllowLandscape ? .allButUpsideDown : .portrait
    }

在需要的时候改变 isAllowLandscape的值即可。

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

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 15,440评论 4 61
  • 很多时候,项目中都有这样的需求:APP中以竖屏为主,个别界面会要求横屏显示,或者要根据用户的手机朝向自动切换横竖屏...
    流火绯瞳阅读 22,458评论 50 62
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 179,234评论 25 708
  • 11.12 昨天,14个人来帮忙,终于,房子顶棚快起来了。技术上没什么好说的,这种房子很简单,只要盖过一次的人都会...
    蛀心虫阅读 224评论 1 1
  • 1. 初看到《深度工作》这种书名我是拒绝的,按二土的话来吐槽,现在是刮起了“深度风”吗,各种“深度学习”以外,又出...
    阿玫小酱当当囧阅读 267评论 0 0

友情链接更多精彩内容