iOS ?關于屏幕強制旋轉的方法

參考鏈接:iOS屏幕旋

  1. 首先選擇支持的旋轉方向(兩種方法,推薦第二種)
    (1)修改Info.plist文件,見圖1
1.png

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

2.png

2.在AppDelegate中添加屬性方法
在.h中添加一個屬性allowRotation

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property(nonatomic,assign)BOOL allowRotation;//是否允許轉向

@end

.m中添加下面的方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(nullable UIWindow *)window{
    if (_allowRotation == YES) {
        return UIInterfaceOrientationMaskLandscapeRight;
    }else{
        return (UIInterfaceOrientationMaskPortrait);
    }
}

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

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

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

//橫豎屏切換按鈕方法
-(void)screen{
    //記著#import "AppDelegate.h"
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
   
    if (_fullScreen ) {//橫屏情況下,點擊此按鈕變為豎屏
        appDelegate.allowRotation = NO;//設置豎屏
        [self setNewOrientation:NO];//調用轉屏代碼
        self.navigationController.navigationBar.hidden = NO;//navbar消失
        [self setViewFrame:NO];//豎屏布局
    }else{//豎屏情況下,點擊此按鈕變為橫屏
        appDelegate.allowRotation = YES;////設置橫屏
        [self setNewOrientation:YES];////調用轉屏代碼
        self.navigationController.navigationBar.hidden = YES;//navbar出現
        [self setViewFrame:YES];//橫屏布局
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容