首先,在iOS中展示界面的方式有兩種,push和modal
那么,在app中如果想要實現(xiàn)隨心所欲的屏幕旋轉(zhuǎn),就要分兩種情況來看
1,使用push,也就是說我們的控制器要嵌套在一個UINavigationController下來展示,我們需要以個繼承了UINavigationController的子類來重寫一下三個方法
- (BOOL)shouldAutorotate{
return self.topViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return self.topViewController.supportedInterfaceOrientations;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return self.topViewController.preferredInterfaceOrientationForPresentation;
}
然后在相應(yīng)的控制器里也要重寫著三個方法,例如這樣
- (BOOL)shouldAutorotate{
return self.autoRotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
return self.mask;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return self.orientation;
}
這里重寫的目的是為了真正控制當(dāng)前的屏幕方向
重寫這三個方法也是做一個鋪墊,真正發(fā)揮改變屏幕方向的代碼是
[[UIDevice currentDevice] setValue:@(UIDeviceOrientationLandscapeLeft) forKey:@"orientation"];
只有重寫了前面的三個方法,上面的代碼才會起作用
以上的步驟的確可以實現(xiàn)屏幕旋轉(zhuǎn),但是無論是modal還是push 我都發(fā)現(xiàn)還存在問題,modal 的情況下會偶發(fā)控制器的view 旋轉(zhuǎn)了但是屏幕的方向沒有變,push 的問題發(fā)生打概率更大一些,就是當(dāng)從A到B變橫屏,然后從B到C變豎屏,再從C返回B能夠變回橫屏,然后從B返回A也能變回豎屏,這時候再從Apush到B則不能變橫屏,這是目前遇到的問題,記錄下來,暫時留在這里,明天繼續(xù)解決。