如何在ios 7中阻止旋转

atr*_*rik 2 iphone objective-c rotation uiview

我使用此代码阻止ios 7之前的旋转(我也使用xibs,现在是storyboard)

- (BOOL)shouldAutorotate {
  return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
 return UIInterfaceOrientationPortrait;
}
Run Code Online (Sandbox Code Playgroud)

现在,我迁移到故事板和ios7它不工作,我的观点仍然在旋转.

更新:我通过将此代码添加到委托来解决这个问题,现在我以前的代码就像魅力一样

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
 NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
 if (self.fullScreenVideoIsPlaying) {
     return UIInterfaceOrientationMaskAllButUpsideDown;
 }
 else {        
     if(self.window.rootViewController){
         UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
         orientations = [presentedViewController supportedInterfaceOrientations];
 }


return orientations;
  }
Run Code Online (Sandbox Code Playgroud)

MGM*_*MGM 5

Atrik的代码有效.这是一个更完整的解决方案,即使使用UINavigationController也只允许纵向模式锁定和解锁

appdelegate .h


@property (nonatomic) BOOL screenIsPortraitOnly;


appdelegate .m

#pragma mark - View Orientation

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{
    NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
    if (self.screenIsPortraitOnly) {
        return UIInterfaceOrientationMaskPortrait;
    }
    else {
        if(self.window.rootViewController){
            UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
            orientations = [presentedViewController supportedInterfaceOrientations];
        }
        return orientations;
    }
}
Run Code Online (Sandbox Code Playgroud)

对于我需要的所有视图控制器Portrait Lock如果您还没有使用导入了app delegate的子类,那么不要忘记导入该委托.对于大多数视图控制器,我使用UIViewController的子类,至少进行输入.

#import "AppDelegate.h"
Run Code Online (Sandbox Code Playgroud)

我将它用于所有纵向锁定的viewcontrollers.

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:true];
    [self portraitLock];
}

-(void) portraitLock {
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = true;
}

#pragma mark - interface posiiton

- (NSUInteger) application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL) shouldAutorotate {
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

ViewDidLoad在viewDidAppear之前运行,所以我在我的UIViewController子类中运行它来解锁所有屏幕.带锁定方法的viewWillAppear仅用于我需要锁定屏幕的cotrollers.

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self portraitUnLock];
}

-(void) portraitUnLock {
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = false;
}
Run Code Online (Sandbox Code Playgroud)