如何更改 Xcode 中特定 ViewController 的方向

How to change the orientation of specific ViewController in Xcode

我想更改 Xcode 中特定 ViewController 的方向。

我制作 a,b,cViewController 并仅将方向 cViewController 更改为 LandscapeRight。 (a和b的方向是纵向)

但如果我改变 cViewController 的方向并将 ViewController 从 c 移动到 b,b 的方向也会更改为 LandscapeRight。 (屏幕转换为推送)

代码:

a 和 bViewController 的 DidLoad

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait]; 
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

cViewController 的 DidLoad

NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight]; 
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];

如何只改变方向 cViewController?

第 1 步

在您的 appdelegate 中创建一个 bool 属性,例如,这个

@property () BOOL restrictRotation;

并调用函数

-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
if(self.restrictRotation)
    return UIInterfaceOrientationMaskLandscape ;
else
    return UIInterfaceOrientationMaskPortrait;
}

第 2 步

并在 C VC

中导入 appdelegate #import "AppDelegate.h"

在你的C VC View 会出现,call like

-(void)viewWillAppear:(BOOL)animated{
// for rotate the VC to Landscape
[self restrictRotationwithNew:YES];
}

(void)viewWillDisappear:(BOOL)animated{
   // rotate the VC to Portait
  [self restrictRotationwithNew:NO];

[super viewWillDisappear:animated];
}


-(void) restrictRotationwithNew:(BOOL) restriction
{
AppDelegate* appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
appDelegate.restrictRotation = restriction;

}

选择2

在你的 C VC 上使用 UIDeviceOrientationDidChangeNotification

的委托函数检查方向
 [[NSNotificationCenter defaultCenter] addObserver:self  selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification  object:nil];



 - (void)orientationChanged:(NSNotification *)notification{


     [self adjustViewsForOrientation:[[UIApplication sharedApplication] statusBarOrientation]];


}

- (void) adjustViewsForOrientation:(UIInterfaceOrientation) orientation    {

UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];

switch (deviceOrientation) {
    case UIDeviceOrientationPortrait:

        NSLog(@"orientationPortrait");
       ;

        break;
    case UIDeviceOrientationPortraitUpsideDown:

        NSLog(@"UIDeviceOrientationPortraitUpsideDown");
        break;
    case UIDeviceOrientationLandscapeLeft:

        NSLog(@"OrientationLandscapeLeft");



        break;
    case UIDeviceOrientationLandscapeRight:

        NSLog(@"OrientationLandscapeRight");

        break;
    default:
        break;
}
}