iOS - 将特定的UIViewController锁定到特定方向

时间:2014-11-19 05:56:41

标签: ios objective-c iphone uiviewcontroller uiinterfaceorientation

我的应用程序支持每4个方向,UIViewController位于LandscapeRight。 我正在使用UINavigationController推送UIViewController,我希望UIViewController仅在UIInterfaceOrientationLandscapeRight,但是当我旋转手机时,它会切换回其他方向。

-(BOOL)shouldAutorotate{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationLandscapeRight;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}

2 个答案:

答案 0 :(得分:8)

只需删除那些shouldAutorotate,supportedInterfaceOrientations和preferredInterfaceOrientationForPresentation。

并将其添加到您想要仅显示横向的viewcontroller。

-(void)viewDidAppear:(BOOL)animated{

    [[UIDevice currentDevice] setValue:
     [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeLeft]
                                forKey:@"orientation"];
} 

实际上,这是来自一个类似的解决方案问题。 How to force view controller orientation in iOS 8?

答案 1 :(得分:2)

您需要创建UIViewController的子类。并在此子类中应用与界面方向相关的更改。扩展要在子类中锁定方向的视图控制器。我将提供一个这样的例子。

我创建的类只显示视图控制器的横向方向。

LandscapeViewControllerUIViewController的子类,您必须在其中处理方向。

<强> LandscapeViewController.h:

#import <UIKit/UIKit.h>

@interface LandscapeViewController : UIViewController

@end

<强> LandscapeViewController.m:

#import "LandscapeViewController.h"

@interface LandscapeViewController ()

@end

@implementation LandscapeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(BOOL)shouldAutorotate {
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
        return YES;
    }
    else {
        return NO;
    }
}

@end

使用上面的子类扩展您的视图控制器。

例如:

#import "LandscapeViewController.h"

@interface SampleViewController : LandscapeViewController

@end