iOS 全局禁止橫屏,個別界面選擇性橫屏的解決辦法

在 APPDelegate.h 文件中增長屬性:是否支持橫屏編程

/***  是否容許橫屏的標記 */
@property (nonatomic,assign)BOOL allowRotation;

在 APPDelegate.m 文件中增長方法,控制所有不支持橫屏app

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if (self.allowRotation) {
        return  UIInterfaceOrientationMaskAllButUpsideDown;
    }
    return UIInterfaceOrientationMaskPortrait;
}

這樣在其餘界面想要橫屏的時候,咱們只要控制 allowRotation 這個屬性就能夠控制其餘界面進行橫屏了。ide

//需在上面#import "AppDelegate.h"
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
//不讓橫屏的時候 appDelegate.allowRotation = NO;便可

界面橫屏 因此這裏能夠使用 通知,就能夠解決atom

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(begainFullScreen) name:UIWindowDidBecomeVisibleNotification object:nil];//進入全屏
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:UIWindowDidBecomeHiddenNotification object:nil];//退出全屏

在退出全屏時,增長邏輯讓其強制編程豎屏,這樣當退出時就會自動變成豎屏了。code

// 進入全屏
-(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];
    }
}

一進入頁面就橫屏:server

NSNumber *orientationTarget = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
//刷新
//    [UIViewController attemptRotationToDeviceOrientation];
相關文章
相關標籤/搜索