最近在本身的項目裏面 有須要作一個需求 : app中某一個頁面支持橫豎屏, 而其餘頁面只能豎屏。
實現方法以下:
1 首先須要Xcode中選中支持的屏幕方向
app
2 Appdelegate中
.h測試
@property (nonatomic,assign)NSInteger allowRotate;
.m中ui
//此方法會在設備橫豎屏變化的時候調用 - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window { // NSLog(@"方向 ============= %ld", _allowRotate); if (_allowRotate == 1) { return UIInterfaceOrientationMaskAll; }else{ return (UIInterfaceOrientationMaskPortrait); } } // 返回是否支持設備自動旋轉 - (BOOL)shouldAutorotate { if (_allowRotate == 1) { return YES; } return NO; }
3 在須要支持橫豎屏的controller中:atom
viewWillApplear 中lua
//在視圖出現的時候,將allowRotate改成1, AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate; delegate.allowRotate = 1;
viewWillDisappear中spa
//在視圖出現的時候,將allowRotate改成0, AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate; delegate.allowRotate = 0;
寫好以上代碼以後, 會發現一些問題: 當橫屏頁面直接點擊「返回」按鈕退出的時候, 頁面依然是橫屏, 而咱們須要的是僅一個頁面能夠橫屏,測試須要在viewWillDisappear中加入以下代碼:code
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) { SEL selector = NSSelectorFromString(@"setOrientation:"); NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]]; [invocation setSelector:selector]; [invocation setTarget:[UIDevice currentDevice]]; int val = UIInterfaceOrientationPortrait; [invocation setArgument:&val atIndex:2]; [invocation invoke]; }
此時就能夠使app僅有設置頁面支持橫豎屏了!圖片
此時若是app要求用戶在橫屏 豎屏的模式下改變UI(橫屏與豎屏對應不一樣的UI), 能夠在如下方法中執行get
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { // do something before rotation if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 屏幕從豎屏變爲橫屏時執行 }else{ 屏幕從橫屏變爲豎屏時執行 } } - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation { // do something after rotation }