ios - 如何在 iOS 8 中强制 View Controller 方向?

在 iOS 8 之前,我们将以下代码与 supportedInterfaceOrientationsshouldAutoRotate 委托(delegate)方法结合使用,以强制应用程序方向为任何特定方向。我使用下面的代码片段以编程方式将应用程序旋转到所需的方向。首先,我正在更改状态栏方向。然后只需呈现并立即关闭模态视图即可将 View 旋转到所需的方向。

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:YES];
UIViewController *c = [[UIViewController alloc]init];
[self presentViewController:vc animated:NO completion:nil];
[self dismissViewControllerAnimated:NO completion:nil];

但这在 iOS 8 中失败了。另外,我在堆栈溢出中看到了一些答案,人们建议我们应该从 iOS 8 开始避免这种方法。

更具体地说,我的应用程序是一种通用类型的应用程序。一共有三个 Controller 。

  1. First View Controller - 它应该支持 iPad 中的所有方向,并且只支持 iPhone 中的纵向(主页按钮向下)。

  2. 第二个 View Controller - 它应该在所有条件下只支持横向

  3. 第三 View Controller - 它应该在所有条件下都只支持横向

我们正在使用导航 Controller 进行页面导航。从第一个 View Controller ,在按钮单击操作中,我们将第二个压入堆栈。因此,当第二个 View Controller 到达时,无论设备方向如何,应用都应该只锁定横向。

下面是我在第二个和第三个 View Controller 中的 shouldAutorotatesupportedInterfaceOrientations 方法。

-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskLandscapeRight;
}

-(BOOL)shouldAutorotate {
    return NO;
}

是否有任何解决方案或任何更好的方法来锁定 iOS 8 的特定方向的 View Controller 。请帮助!!

最佳答案

对于 iOS 7 - 10:

objective-C :

[[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeLeft) forKey:@"orientation"];
[UINavigationController attemptRotationToDeviceOrientation];

swift 3:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UINavigationController.attemptRotationToDeviceOrientation()

只需在呈现的 View Controller 的 -viewDidAppear: 中调用它。

关于ios - 如何在 iOS 8 中强制 View Controller 方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26357162/

相关文章:

ios - 属性 "Nonatomic"是什么意思?

ios - 如何在代码中获取我的 iOS 项目的当前版本?

ios - 为现有对象添加扩展名的 Swift 文件命名的最佳实践是什么?

objective-c - 在 Cocoa 中生成一个随机的字母数字字符串

objective-c - 我如何判断一个对象是否附加了键值观察器

iphone - Objective-C 的 JSON 解析器比较(JSON 框架、YAJL、Tou

iphone - 在 iOS 中将 HTML 转换为 NSAttributedString

ios - 如何将我的设备 token (NSData) 转换为 NSString?

ios - 如何获取在 UIWebView 中显示的 HTML 页面的标题?

objective-c - 拆分一个 NSString 以访问一个特定的片段