iOS- 将特定的UIViewController锁定为特定的方向[关闭]

问题描述 投票:3回答:2

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

-(BOOL)shouldAutorotate{
    return NO;
}

-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationLandscapeRight;
}

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
}
ios objective-c iphone uiviewcontroller uiinterfaceorientation
2个回答
8
投票

只需删除那些应该自动旋转,supportedInterfaceOrientations和preferredInterfaceOrientationForPresentation。

并将其添加到只想显示横向的视图控制器中。

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UIDevice currentDevice] setValue:
     [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeLeft]
                                forKey:@"orientation"];
} 

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


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
© www.soinside.com 2019 - 2024. All rights reserved.