我正在制作一个iPhone应用程序,我需要它处于纵向模式,所以如果用户侧向移动设备,它不会自动旋转。我怎样才能做到这一点?
要禁用特定视图控制器的方向,您现在应该覆盖supportedInterfaceOrientations
和preferredInterfaceOrientationForPresentation
。
- (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中弃用。
对于那些错过它的人:您可以使用项目设置屏幕来修复整个应用程序的方向(无需覆盖每个控制器中的方法):
它就像切换支持的接口方向一样简单。您可以通过单击左侧面板中的项目>应用程序目标>摘要选项卡找到。
Swift 3如果你有一个navigationController,那就像这样子类(仅限肖像):
class CustomNavigationViewController: UINavigationController {
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return UIInterfaceOrientation.portrait
}
}
从您的班级中删除方法shouldAutorotateToInterfaceOrientation
也完全有效。如果你不计划旋转,那么在你的课程中使用这个方法是没有意义的,代码越少越好,保持干净。