Swift-横竖屏切换

来源:互联网 发布:人工智能文献 编辑:程序博客网 时间:2024/06/07 04:03

XCode中,我们一般通过以下方式来设置横竖屏

这样设置的话,就能让整个应用固定横竖屏。但是,有时候应用中要求某些页面需要固定竖屏,某些页面支持横竖屏切换,这时,上述方式就无法满足,我们需要额外做一些代码上的设置

首先,在AppDelegate中

声明一个变量来判断页面是否支持横竖屏,默认情况下为0,表示不支持
var allowRotation = 0

实现以下方法,用于实现页面是否支持横竖屏

func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {        if allowRotation == 1 {            if !UIApplication.shared.statusBarOrientation.isPortrait {                return UIInterfaceOrientationMask.portrait            }else{                return UIInterfaceOrientationMask.landscapeLeft            }        }else{            return UIInterfaceOrientationMask.portrait        }    }

接着在相关的ViewCOntroller中设置,就可以实现屏幕横竖屏切换

let appDelegate = UIApplication.shared.delegate as! AppDelegateappDelegate.allowRotation = 1 //1表示支持横竖屏

注意:如果是通过代码设置rootViewController的,建议将下图中Main Interface的Main删掉,MainStoryController就不要删了,如果真机测试的话记得把屏幕旋转打开

Demo链接
!(https://github.com/MrLinTianbao/Toggle-Screen.git)

原创粉丝点击