ios 旋转屏幕试图切换_iOS屏幕横竖屏切换

iOS屏幕横竖屏切换

胡东东博客 • 2020 年 10 月 25 日

搜了网上的教程是真的乱,废话不多说,这里从启动到具体的VC,横竖屏切换完美搞定。

如果你的app只需要支持一个方向,那么不需要看以下内容,只需要将项目的General设置中,将Device Orientation勾选需要支持的方向即可

一、启动页LaunchScreen

启动页是系统的默认根据info.plist的设置显示,启动时就加载了,加载时机很早,所以你要决定启动页要不要根据手机横竖屏自动旋转,还是保持固定的方向。

1.1、启动页需要根据手机横竖屏自动旋转

如果启动页需要根据手机横竖屏自动旋转,只需要在项目的General设置中,将Device Orientation勾选需要支持的方向即可。这样在横屏或者竖屏启动时会默认加载指定的方向

1.2、启动页固定方向,后续VC支持旋转

正如上面说的启动页加载很早,所以需要在info.plist固定方向,在Appdelegate里面设置VC支持的旋转方向,例如启动页固定竖屏,VC支持横竖屏在项目的General设置中,将Device Orientation只勾选Portrait

在Appdelegate中动态设置支持的旋转方向func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

return .all

}

二、控制器VC的旋转设置

控制器VC的旋转会根据顶部的VC设置,所以看你是否用了导航控制器navigationController和tabbarController,如果是嵌套使用,除了设置指定的VC控制器,还需要设置navigationController和tabbarController的属性,可以自定义这两个子类。

2.1、tabbarController的子类实现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

}

2.2、navigationController的子类实现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

}

2.3、指定VC的实现//是否需要自动旋转

override var shouldAutorotate: Bool {

return false

}

//支持的旋转方向

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {

return .portrait

}

//跳转的优先方向

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {

return .portrait

}

三、跳转

跳转记得用present的跳转方式self.present(VC, animated: true) {

}版权属于:胡东东博客

自2017年12月26日起,『转载以及大段采集进行后续编辑』须注明本文标题和链接!否则禁止所有转载和采集行为!

☟☟如文章有用,可点击一次下方广告支持一下☟☟


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部