最近在项目中,遇到了大多数界面均为竖屏,但是有几个界面需要支持横屏的情况,在此记录一下如何实现(支持某个页面指定屏幕方向
)。
1.设置app支持的方向
设置app仅支持竖屏
TARGETS->Genreal->Deployment Info->Device Orentation
image.png
2. 设置View controller-based status bar appearance
在info.plist文件中 添加View controller-based status bar appearance
字段,值设为YES
YES:代表控制器对状态栏设置的优先级高于application
NO:代表application为准,控制器设置状态栏prefersStatusBarHidden是无效的的根本不会被调用
3. 通过AppDelegate实现
- 声明屏幕支持的方向私有属性
orientation
private var orientation: UIInterfaceOrientationMask = UIInterfaceOrientationMask.portrait
- 我这里封装了一个public方法用来实现更改屏幕支持的方向
/// 设置屏幕是否允许旋转
/// - Parameters:
/// - allowRoation: 是否允许旋转
/// - orientation: 旋转方向
public func setOrientaition(allowRoation: Bool, orientation: UIInterfaceOrientationMask) {
self.orientation = orientation
if allowRoation == false {
self.orientation = .portrait
// 设置为竖屏时强制旋转屏幕
UIDevice.current.setValue(UIDeviceOrientation.portrait.rawValue, forKey: "orientation")
} else {
switch orientation {
case .landscapeLeft:
// 设置为左横屏时强制旋转屏幕
UIDevice.current.setValue(UIDeviceOrientation.landscapeLeft.rawValue, forKey: "orientation")
break
case.landscapeRight:
// 设置为右横屏时强制旋转屏幕
UIDevice.current.setValue(UIDeviceOrientation.landscapeRight.rawValue, forKey: "orientation")
break
default:
break
}
}
}
如果不需要设置屏幕强制,可以根据需求对方法进行自定义。。。
一定要实现下边的方法!!!
//控制屏幕支持的方向
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
return self.orientation
}
4.调用
在需要支持横屏的页面中的viewWillAppear
中设置一下
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// 允许全屏
wlAppDelegate?.setOrientaition(allowRoation: true, orientation: .allButUpsideDown)
}
退出需要支持横屏的页面时,需要调用下viewDidAppear
方法
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
wlAppDelegate?.setOrientaition(allowRoation: false, orientation: .portraitUpsideDown)
}
为了便于在项目中快捷的调用AppDelegate,声明了一个全局变量。
let wlAppDelegate = UIApplication.shared.delegate as? AppDelegate