iOS 处理旋转某些ViewController屏幕的问题

2018-07-26  本文已影响166人  FicowShen



常见的应用都是以竖屏启动的,在启动后只有某些ViewController才需要进行横屏显示。
按照本教程配置,可确保应用以竖屏启动,在需要旋转屏幕的ViewController中可进行屏幕旋转。


1.在项目设置中,设置屏幕方向:

设置屏幕方向

这里有一个注意事项,如果你要确保应用是以竖屏启动的,就一定不要勾选其他方向!

2.在AppDelegate中添加以下代码:

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        return .allButUpsideDown
    }

这里,除了倒转方向,其他都支持,按照个人需求进行配置即可。

3.如果根ViewController是TabBarContoller,添加以下代码:

    override var shouldAutorotate: Bool{
        return self.selectedViewController?.shouldAutorotate ?? false
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return self.selectedViewController?.supportedInterfaceOrientations ?? .portrait
    }
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return self.selectedViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }

4.如果使用了UINavigationController,使用自定义的类继承UINavigationController,在这个自定义的类中添加以下代码:

    override var shouldAutorotate: Bool{
        return self.topViewController?.shouldAutorotate ?? false
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return self.topViewController?.supportedInterfaceOrientations ?? .portrait
    }
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        return self.topViewController?.preferredInterfaceOrientationForPresentation ?? .portrait
    }

5.在需要旋转屏幕的ViewController中添加以下代码:

    override var shouldAutorotate: Bool{
        return true
    }
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .landscapeRight  // 支持的屏幕方向,根据个人需求进行配置
    }

6.然后,在需要旋转屏幕的ViewController中添加以下代码,根据个人需要调用此方法即可实现屏幕旋转,并及时更新所有控件的布局:

    public static func setScreenOrientation(_ orientation:UIInterfaceOrientation){
        
        var value = UIInterfaceOrientation.unknown.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
        
        value = orientation.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }

7.最后,在离开已旋转的ViewController时,将屏幕旋转方向恢复原始值(否则会遭遇bug),调用上面定义的setScreenOrientation()方法即可。




参考资料:
ios启动页强制竖屏(进入App后允许横屏与竖屏)
完美解决 iOS 中只旋转自己想要旋转的屏幕
iOS指定页面屏幕旋转,手动旋转

上一篇下一篇

猜你喜欢

热点阅读