如何禁用横向方向?

use*_*652 30 iphone xcode objective-c orientation ios

我正在制作一个iPhone应用程序,我需要它处于纵向模式,所以如果用户侧向移动设备,它不会自动旋转.我怎样才能做到这一点?

the*_*ner 51

要禁用特定View Controller的方向,您现在应该覆盖supportedInterfaceOrientationspreferredInterfaceOrientationForPresentation.

- (NSUInteger) supportedInterfaceOrientations {
    // Return a bitmask of supported orientations. If you need more,
    // use bitwise or (see the commented return).
    return UIInterfaceOrientationMaskPortrait;
    // return UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
}

- (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation {
    // Return the orientation you'd prefer - this is what it launches to. The
    // user can still rotate. You don't have to implement this method, in which
    // case it launches in the current orientation
    return UIInterfaceOrientationPortrait;
}
Run Code Online (Sandbox Code Playgroud)

如果您的目标是iOS 6之前的版本,则需要使用该shouldAutorotateToInterfaceOrientation:方法.通过更改何时返回yes,您将确定它是否将旋转到所述方向.这只允许正常的纵向方向.

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 

    // Use this to allow upside down as well
    //return (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}
Run Code Online (Sandbox Code Playgroud)

请注意,shouldAutorotateToInterfaceOrientation:iOS 6.0中已弃用.

  • 如果视图控制器在导航控制器中,则导航控制器是需要实现这些控制器的地方. (2认同)

sky*_*der 38

Xcode 5及以上版本

  • 在左侧边栏的Project Navigator中单击您的项目以打开项目设置
  • 转到" 常规"选项卡.
  • 在" 设备方向"下的" 部署信息"部分中取消选中您不需要的选项

截图显示了点击的位置


Tho*_*eek 28

Xcode 4及以下

对于那些错过它的人:您可以使用项目设置屏幕来修复整个应用程序的方向(无需覆盖每个控制器中的方法):

在此输入图像描述

它就像切换支持的接口方向一样简单.您可以通过单击左侧面板中的项目>应用程序目标>摘要选项卡找到.


Joh*_*ton 9

在 Xcode 13.3.1 中,仅取消选中不需要的方向并不会阻止应用程序支持所有旋转。有必要进入该Build Settings选项卡并手动从以下字段中删除您不希望支持的任何方向: 所需的方向值

就我而言,我的应用程序现在仅支持纵向。


iOS*_*iOS 6

如果您想禁用iPhone 和 iPad的横向方向。

转至“目标”并转至“常规”选项卡。请参阅下面的屏幕并取消选择横向左和横向右

在此输入图像描述

在这种情况下,只有 iPhone 横向模式将被禁用,而 iPad 则不会。对于 iPad,所有模式均已启用。如果您想选择从通用到 iPad 的设备选项。它看起来像这样。请参见下面的屏幕。

在此输入图像描述

现在您需要取消选择除 iPad肖像之外的所有模式。请参阅下面的屏幕截图。

在此输入图像描述

现在,您已成功禁用所有设备除纵向之外的所有模式。


Ano*_*mys 6

适用于 iPhone 和 iPad(通用)的最简单的解决方案 - 它删除了info.plist文件或Project -> Info -> Custom iOS Target Properties中不必要的方向。

只需从列表中添加或删除方向项:

  • 支持的接口方向iPhone
  • 支持的接口的取向总览ipad公司

在此处输入图片说明

  • 我刚刚尝试过这个,但我必须将“支持的界面方向”替换为“支持的界面方向(iPhone)”,否则它会覆盖iPad设置。 (2认同)

Sof*_*ner 5

如果您创建了一个新的 Xcode 13.3 项目并在“项目”>“常规”>“部署”中取消选中不必要的方向复选标记,则没有帮助。检查 Target > Build Settings - 有 2 行覆盖全局设置。

构建设置