前言
在開發中有時會碰到旋轉屏幕的需求,例如直播時橫豎屏推流,這里我使用的一種方法時用純代碼強制翻轉,其他晚上方法也都使用過,但是效果并不好,目前這個方法還可以。
步驟
- 1.AppDelegate中配置
//AppDelegate.h
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
//允許橫屏
@property (nonatomic, assign) BOOL allowLandscapeRight;
@end
//AppDelegate.m 增加此方法
//橫豎屏切換使用
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if (self.allowLandscapeRight) {
return UIInterfaceOrientationMaskLandscapeRight;
}
return UIInterfaceOrientationMaskPortrait;
}
- 2.在要跳轉的界面
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowLandscapeRight = YES;
//強制旋轉成全屏
NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationLandscapeLeft];
[[UIDevice currentDevice]setValue:value forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
[self.navigationController pushViewController:[[YouVC alloc] init] animated:YES];
- 3.在退出的時候
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
appDelegate.allowLandscapeRight = NO;
//強制旋轉成豎屏
NSNumber *value = [NSNumber numberWithInt:UIDeviceOrientationPortrait];
[[UIDevice currentDevice]setValue:value forKey:@"orientation"];
[UIViewController attemptRotationToDeviceOrientation];
}
問題
可能會碰到狀態欄不顯示的問題,詳見我的上一篇文章 iOS 狀態欄更改顏色、適配等