为了账号安全,请及时绑定邮箱和手机立即绑定

如何在iOS 7中以编程方式设置设备方向?

如何在iOS 7中以编程方式设置设备方向?

iOS
杨__羊羊 2019-10-08 09:51:58
我正在使用AutoLayout在iPad应用程序上工作,如果用户启用某种模式(“平视”模式),则我只希望支持纵向(或纵向颠倒)方向,并且如果设备处于风景,我想自动切换到人像模式。在顶视图控制器中,我具有以下内容:- (NSUInteger) supportedInterfaceOrientations {    if (self.modeHeadsUp) {        return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;    } else {        return UIInterfaceOrientationMaskAll;    }}- (BOOL) shouldAutorotate {    return TRUE;}根据我在其他地方看到的答案,答案似乎是我应该使用“ application setStatusBarOrientation”。因此,在用户选择“抬头”模式的方法中,我包括:    UIApplication *application = [UIApplication sharedApplication];    [application setStatusBarOrientation:UIInterfaceOrientationPortrait                                animated:YES];但是,这似乎没有任何作用。虽然我可以物理移动设备以使其旋转成纵向,但它不会自动旋转。实际上,当在运行上述代码以编程方式设置方向之后处于横向模式时,当我使用以下代码查询应用程序“ statusBarOrientation”时,对于横向而言,它保持在“ 4”:UIApplication *application = [UIApplication sharedApplication];int orientation = [application statusBarOrientation];self.movesTextView.text = [NSString stringWithFormat:@"ORIENTATION %d", orientation];似乎没有用setStatusBarOrientation触发自动布局,所以我尝试在此之后添加以下代码,但没有任何效果:    [super updateViewConstraints];    [self.view updateConstraints];我意识到Apple希望将设备定位交给用户。但是,我希望能够在不使用“平视”模式时支持横向模式。我是否缺少能够强制改变方向的东西?
查看完整描述

3 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

对于iOS 7和8:


目标C:


NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];

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

迅捷3+:


let value = UIInterfaceOrientation.landscapeLeft.rawValue

UIDevice.current.setValue(value, forKey: "orientation")

我叫它- viewDidAppear:。


查看完整回答
反对 回复 2019-10-08
?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

用这个。定向问题的完美解决方案..ios7和更早版本


[[UIDevice currentDevice] setValue:

    [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]

        forKey:@"orientation"];


查看完整回答
反对 回复 2019-10-08
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

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

确实可以,但是您必须在视图控制器中返回shouldAutorotate并使用YES


- (BOOL)shouldAutorotate

{

    return self.shouldAutoRotate;

}

但是,如果这样做,如果用户旋转设备,VC将自动旋转...因此我将其更改为:


@property (nonatomic, assign) BOOL shouldAutoRotate;


- (BOOL)shouldAutorotate

{

    return self.shouldAutoRotate;

}

我打电话


- (void)swithInterfaceOrientation:(UIInterfaceOrientation)orientation

{

    self.rootVC.shouldAutoRotate = YES;


    NSNumber *value = [NSNumber numberWithInt: orientation];

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

}

单击按钮以强制新的方向。要将shouldAutoRotate设置为NO,我将其添加到了rootVC


- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation

{

    self.shouldAutoRotate = NO;

}

PS:此替代方法也适用于所有模拟器。


查看完整回答
反对 回复 2019-10-08
  • 3 回答
  • 0 关注
  • 403 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信