【发布时间】:2012-07-31 21:39:49
【问题描述】:
我正在制作一个 iPhone 应用程序,我需要它处于纵向模式,因此如果用户将设备侧向移动,它不会自动旋转。我该怎么做?
【问题讨论】:
标签: iphone objective-c ios xcode orientation
我正在制作一个 iPhone 应用程序,我需要它处于纵向模式,因此如果用户将设备侧向移动,它不会自动旋转。我该怎么做?
【问题讨论】:
标签: iphone objective-c ios xcode orientation
要禁用特定视图控制器的方向,您现在应该覆盖supportedInterfaceOrientations 和preferredInterfaceOrientationForPresentation。
- (UIInterfaceOrientationMask)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: 方法。通过更改它何时返回是,您将确定它是否会旋转到所述方向。这将只允许正常的纵向。
- (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 中已被弃用。
【讨论】:
NSUinteger 从 supportedInterfaceOrientations(第一行代码)替换为 UIInterfaceOrientationMask。 Xcode 8 警告“在 'supportedInterfaceOrientations' 的实现中返回类型冲突:'UIInterfaceOrientationMask' (aka 'enum UIInterfaceOrientationMask') vs 'NSUInteger' (aka 'unsigned long')”这很有意义。谢谢你的回答?
【讨论】:
对于那些错过它的人:您可以使用项目设置屏幕来修复整个应用程序的方向(无需覆盖每个控制器中的方法):
就像切换支持的界面方向一样简单。您可以通过单击左侧面板中的项目 > 应用程序目标 > 摘要选项卡来找到。
【讨论】:
斯威夫特 3 如果你有一个 navigationController,像这样子类化它(仅用于纵向):
class CustomNavigationViewController: UINavigationController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
【讨论】:
从您的类中完全删除方法 shouldAutorotateToInterfaceOrientation 也可以。如果你不打算轮换,那么在你的类中使用该方法是没有意义的,代码越少越好,保持干净。
【讨论】:
shouldAutorotateToInterfaceOrientation 已被弃用多年。