搜了网上的教程是真的乱,废话不多说,这里从启动到具体的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) {
}
版权属于:胡东东博客
本文链接:http://blog.hudongdong.com/ios/1095.html
自2017年12月26日起,『转载以及大段采集进行后续编辑』须注明本文标题和链接!否则禁止所有转载和采集行为!
☟☟如文章有用,可点击一次下方广告支持一下☟☟
干脆利落