【问题标题】:How to change device orientation when app returns to foreground in iOS?当应用程序在 iOS 中返回前台时如何更改设备方向?
【发布时间】:2016-01-12 09:46:48
【问题描述】:

我已使用以下代码在子视图控制器中将方向从纵向更改为横向


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

但是当我转到后台并返回前台时,我按下按钮转到主页然后需要使用以下代码将方向从横向更改为纵向


    NSNumber *value = [NSNumber      numberWithInt:UIInterfaceOrientationPortrait];

    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if ([ConfigObjC currentPage] && [[ConfigObjC currentPage] isEqualToString:@"SubViewController"])
    {
        return UIInterfaceOrientationMaskLandscapeLeft;
    }
    else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

但它不起作用。

当我不去背景时,我已经成功地将方向从横向更改为纵向。怎么解决这个问题非常感谢

【问题讨论】:

    标签: ios screen orientation screen-orientation


    【解决方案1】:

    如果您想将窗口置于横向模式,您可以修改 Xcode 信息以仅支持横向,如下所示:

    <key>UISupportedInterfaceOrientations</key>
    <array>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
    </array>
    

    另一种编码方式是改变UIWindow的方向,像这样:

    UIApplication *application=[UIApplication sharedApplication];
    [application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
    application.keyWindow.transform=CGAffineTransformMakeRotation(M_PI);
    

    使用上面这种方式需要设置ShouldAutoRotateNO

    - (BOOL)shouldAutorotate{
        return NO;
    }
    

    此外,如果只有几个视图以横向模式显示,您可以使用属性transform 来旋转这些视图,如下所示:

    //rotate screen only with view
    [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
    
    self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
    

    希望能帮到你!

    【讨论】:

    • 我已经使用下面的代码 NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft]; [[UIDevice currentDevice] setValue:value forKey:@"orientation"];,但是当我进入后台并返回前台时,我尝试使用 NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait] 将方向更改为纵向[[UIDevice currentDevice] setValue:value forKey:@"orientation"];它不起作用
    • UIDeviceOrientation 是只读的,UIInterfaceOrientation 是读写的。您可以使用 UIDeviceOrientation 注册通知,然后旋转屏幕和视图
    猜你喜欢
    • 1970-01-01
    • 2017-04-13
    • 2017-08-25
    • 2017-09-15
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    相关资源
    最近更新 更多