大部分页面都是竖屏,只有两个页面是横屏,点击强制旋转屏幕

最近做项目遇到一个需求,就是大部分页面都是竖屏,只有两个页面是横屏,这就要用到强制旋转屏幕了。我查了网上的资料,人云亦云者众多,但是真正有效的很少,所以干脆我自己总结一个吧,demo见底部,文章里所有代码和设置都是demo里的。

OC版点这里第一步:设置项目属性为只允许竖屏

 需要注意的是,iPad需要在info.plist里设置:

第二步:AppDelegate里的代码

class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var isForceLandscape: Bool = falsevar isForcePortrait: Bool = false func application(_ application: UIApplication, didFinishLaunchingWithOptionslaunchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow.init(frame: UIScreen.main.bounds) window?.backgroundColor = UIColor.white window?.rootViewController =UINavigationController.init(rootViewController: ViewController.init()) window?.makeKeyAndVisible() return true }func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask { if (isForceLandscape) { //这里设置允许横屏的类型 return .landscapeRight; }else if(isForcePortrait){ return .portrait; } return .portrait; } }

第三步:在控制器里的代码,demo是写在控制器的基类BaseViewController里的

 

class BaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } ///强制横屏 func forceOrientationLandscape() { let appdelegate = UIApplication.shared.delegate as! AppDelegate appdelegate.isForceLandscape = true appdelegate.isForcePortrait = false appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window) //强制翻转屏幕,Home键在右边。 UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation") //刷新 UIViewController.attemptRotationToDeviceOrientation() } ///强制竖屏 func forceOrientationPortrait() { let appdelegate = UIApplication.shared.delegate as! AppDelegate appdelegate.isForceLandscape = false appdelegate.isForcePortrait = true appdelegate.application(UIApplication.shared, supportedInterfaceOrientationsFor: self.view.window) //强制翻转屏幕,Home键在右边。 UIDevice.current.setValue(UIInterfaceOrientation.portrait.rawValue, forKey: "orientation") //刷新 UIViewController.attemptRotationToDeviceOrientation() } }

第四步:使用,demo里是TestViewController 使用横屏,ViewController 使用竖屏:

在 TestViewController里使用强制横屏:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值