- UIViewController強制豎屏:
如果想整個APP豎屏,可以寫一個BaseViewcontroller
1 先在AppDelegate.m里面重寫如下方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
//返回你要支持的屏幕方向,如果只支持豎屏,直接返回豎屏的宏
}
2 在UIViewController的
- (void)viewWillAppear:(BOOL)animated{
//interfaceOrientation為方向宏定義
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:interfaceOrientation] forKey:@"orientation"];
}
- 整體豎屏,但是個別界面需要橫屏
如果界面中有個別界面需要橫屏,可以增加一個標志位來控制supportedInterfaceOrientationsForWindow的返回值,比如:
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (!self.allowRotation) {
return UIInterfaceOrientationMaskPortrait;
}
return UIInterfaceOrientationMaskLandscapeRight; //界面只能往右旋轉
}
然后在你需要橫屏的UIViewController代碼里面如下實現:(記得橫屏標志位的值設置)
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}
- 兼容性問題
preferredInterfaceOrientationForPresentation這個方法在不同IOS版本的定義是不一樣的。
<IOS9:
- (NSUInteger)preferredInterfaceOrientationForPresentation {
return UIInterfaceOrientationPortrait;
}
>=IOS9
- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
return UIInterfaceOrientationMaskPortrait;
}
注意如果重寫了supportedInterfaceOrientations方法,那么在IOS7版本中從橫屏切換到豎屏會存在切換不過來的問題。我當時就是在UIViewControler里面重寫了
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
最后為了解決IOS7版本的問題,需要把如上重寫刪除。
同時注意UIViewController里面的interfaceOrientation屬性也是在IOS8以后就不建議使用了。