我的应用程序支持每4个方向,我在UIViewController
中有一个LandscapeRight
。我正在使用UINavigationController
推动UIViewController
,我希望UIViewController
仅出现在UIInterfaceOrientationLandscapeRight
中,但是当我旋转手机时,它会切换回其他方向。
-(BOOL)shouldAutorotate{
return NO;
}
-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationLandscapeRight;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return UIInterfaceOrientationLandscapeRight;
}
只需删除那些应该自动旋转,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?
您需要创建UIViewController
的子类。并在此子类中应用与界面方向相关的更改。扩展您要在其中使用子类锁定方向的视图控制器。我将提供一个示例。
我创建了只显示视图控制器横向方向的类。
[LandscapeViewController
是UIViewController
的子类,您必须在其中处理方向。
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