不少 App 並沒有做橫屏適配,全局都希望鎖定在豎屏。但在播放視頻的場景下,用戶往往希望全屏時能橫過來觀看,退出後又恢復豎屏。系統並沒有現成的 API 直接滿足這種「全局豎屏、局部橫屏」的需求,因此需要我們自己動手控制。
這種情況處理起來比較簡單,思路是通過 AppDelegate 中的一個開關屬性來統一控制方向。
首先在 AppDelegate.h 中新增一個標記屬性:
/*** 是否允許橫屏的標記 */ @property (nonatomic, assign) BOOL allowRotation;
接著在 AppDelegate.m 中實現方法,讓全局默認不支持橫屏:
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation) {
return UIInterfaceOrientationMaskAllButUpsideDown;
}
return UIInterfaceOrientationMaskPortrait;
}
這樣一來,任何界面想要橫屏,只需切換 allowRotation 這個開關即可:
// 需在上面 #import "AppDelegate.h" AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; appDelegate.allowRotation = YES; // 允許橫屏 // 不允許橫屏時 appDelegate.allowRotation = NO;
播放頁的橫屏控制可以借助 UIWindow 的通知來完成。當全屏窗口出現或消失時,我們分別切換方向開關:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil]; // 進入全屏 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil]; // 退出全屏
在退出全屏時,除了關閉橫屏開關,還要強制把方向擺正回豎屏。這樣當用戶點擊「完成」退出全屏時,界面會自動回到豎屏狀態:
// 進入全屏
-(void)begainFullScreen {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = NO;
// 強制歸正
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];
}
}
另一種常見做法是建立一個 BaseViewController,讓其他控制器都繼承自它,並在基類裡統一禁止橫屏;只有個別需要橫屏的頁面再單獨打開開關即可。這樣管理起來更加集中,也便於後續維護。