如何禁用横向方向?

问题描述 投票:29回答:7

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

iphone objective-c ios xcode orientation
7个回答
51
投票

要禁用特定视图控制器的方向,您现在应该覆盖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;
}

如果你的目标是比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);
}

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


38
投票

Xcode 5 and above

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


28
投票

Xcode 4 and below

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

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


1
投票

Swift 3如果你有一个navigationController,那就像这样子类(仅限肖像):

class CustomNavigationViewController: UINavigationController {

  override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
  }

  override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
  }
}

1
投票

如果要禁用iPhone和iPad的横向打印。

转到目标并转到常规选项卡。请参阅以下屏幕并取消选择左侧横向和右侧横向。

enter image description here

在这种情况下,只有iPhone横向模式将被禁用,而不是iPad。对于iPad,所有模式都是可用的。如果您想从Universal到iPad选择设备选项。它看起来像这样。见下面的屏幕。

enter image description here

现在您需要取消选择除Portrait for iPad之外的所有模式。见下面的截图。

enter image description here

现在,您已成功禁用除Portrait以外的所有模式。


0
投票

从您的班级中删除方法shouldAutorotateToInterfaceOrientation也完全有效。如果你不计划旋转,那么在你的课程中使用这个方法是没有意义的,代码越少越好,保持干净。


0
投票

Xcode 8,Xcode 9,Xcode 10及以上版本

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.