iOS 屏幕橫豎屏轉換的方法

首先選擇支持的旋轉方向(兩種方法,推薦第二種)

(1)修改Info.plist文件,見圖1

(2)直接上圖,(勾選即可)

2.在AppDelegate中添加屬性方法

在.h中添加一個屬性allowRotation

@interfaceAppDelegate: UIResponder@property(strong, nonatomic) UIWindow *window;@property(nonatomic,assign)BOOL allowRotation;//是否允許轉向@end

.m中添加下面的方法

- (UIInterfaceOrientationMask)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(nullableUIWindow*)window{if(_allowRotation ==YES) {returnUIInterfaceOrientationMaskLandscapeRight;? ? }else{return(UIInterfaceOrientationMaskPortrait);? ? }}

3.在你需要旋轉的控制器.m中添加一下方法

- (void)setNewOrientation:(BOOL)fullscreen{if(fullscreen) {NSNumber*resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown];? ? ? ? [[UIDevicecurrentDevice] setValue:resetOrientationTarget forKey:@"orientation"];NSNumber*orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationLandscapeRight];? ? ? ? [[UIDevicecurrentDevice] setValue:orientationTarget forKey:@"orientation"];? ? }else{NSNumber*resetOrientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationUnknown];? ? ? ? [[UIDevicecurrentDevice] setValue:resetOrientationTarget forKey:@"orientation"];NSNumber*orientationTarget = [NSNumbernumberWithInt:UIInterfaceOrientationPortrait];? ? ? ? [[UIDevicecurrentDevice] setValue:orientationTarget forKey:@"orientation"];? ? }}

4.點擊旋轉按鈕調用- (void)setNewOrientation:(BOOL)fullscreen方法

//橫豎屏切換按鈕方法-(void)screen{//記著#import "AppDelegate.h"AppDelegate * appDelegate = (AppDelegate *)[UIApplicationsharedApplication].delegate;if(_fullScreen ) {//橫屏情況下,點擊此按鈕變為豎屏appDelegate.allowRotation =NO;//設置豎屏[selfsetNewOrientation:NO];//調用轉屏代碼self.navigationController.navigationBar.hidden =NO;//navbar消失[selfsetViewFrame:NO];//豎屏布局}else{//豎屏情況下,點擊此按鈕變為橫屏appDelegate.allowRotation =YES;////設置橫屏[selfsetNewOrientation:YES];////調用轉屏代碼self.navigationController.navigationBar.hidden =YES;//navbar出現[selfsetViewFrame:YES];//橫屏布局}}

3.獲取當前屏幕是豎屏還是橫屏

#import"AppDelegate.h"

@interfaceJGCameraViewController()

@property(nonatomic,assign)UIInterfaceOrientationinterfaceOrientation;

@end

- (void)viewWillAppear:(BOOL)animated {

[superviewWillAppear:animated];//改變AppDelegate的appdelegete.allowRotation屬性AppDelegate*appdelegete = (AppDelegate*)[UIApplicationsharedApplication].delegate;appdelegete.allowRotation=YES;self.interfaceOrientation=1;

}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {

self.interfaceOrientation= interfaceOrientation;switch(interfaceOrientation) {caseUIInterfaceOrientationPortrait://home健在下break;

caseUIInterfaceOrientationPortraitUpsideDown:

//home健在上

break;

caseUIInterfaceOrientationLandscapeLeft:

//home健在左

break;

caseUIInterfaceOrientationLandscapeRight://home健在右

break;

default:

break;

}

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容