牛B的swift屏幕旋转经验终结者(OC统一思路)
1、AppDelegate
(1)定义变量 var blockRotation: Bool = false
(2)定义方法
Swift代码
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if self.blockRotation{
return UIInterfaceOrientationMask.All
} else {
return UIInterfaceOrientationMask.Portrait
}
}
2、要横屏的viewController
(1)获取变量
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
(2)在viewDidLoad中修改blockRotation变量值
override func viewDidLoad() {
super.viewDidLoad()
appDelegate.blockRotation = true
}
(3)viewWillAppear 设置页面横屏
override func viewWillAppear(animated: Bool) {
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
(4)viewWillDisappear设置页面转回竖屏
override func viewWillDisappear(animated: Bool) {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
(5)横屏页面是否支持旋转
// 是否支持自动横屏。看项目可调,可以设置为true
override func shouldAutorotate() -> Bool {
return false
}
经验总结:
上面情况是一个界面竖屏跳转到第二个横屏界面。
需要一个界面可以竖屏,然后想竖屏播放器那样突然来个横屏,怎么办,接下来就是放大招了:
给想要横屏或者竖屏调用下面的动作。
// MARK: - 横屏
func hengp() {
appDelegate.blockRotation = true
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// MARK: - 竖屏
func shup() {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// 将要发生旋转就触发代理
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}
// 旋转完成触发代理。我们需要在这里对必要的界面设置重新布局
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
// 获取当前手机物理状态的屏幕模式,看看是横屏还是竖屏.
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
if(interfaceOrientation == UIInterfaceOrientation.Portrait)
{
//当前是在竖屏模式
print("竖屏")
}else{
//当前是在横屏模式
self.theWebView?.frame = self.view.frame
}
}
记住:横屏后,和竖屏前的宽高度值是会变的,如果你有缓存保存了宽高度值,在这种情况下,横屏后获取到以前竖屏的保存的宽高度值,一定要重新获取,
let bWidth = CGRectGetWidth(UIScreen.mainScreen().bounds) ///< 屏幕宽度
let bHeight = CGRectGetHeight(UIScreen.mainScreen().bounds) ///< 屏幕高度