iOS – 将特定的UIViewController锁定到特定方向
我的应用程序支持每4个方向,我有一个在LandscapeRight
的UIViewController
。 我正在使用UINavigationController
来推送UIViewController
,我希望UIViewController
仅在UIInterfaceOrientationLandscapeRight
但是当我旋转手机时,它会切换回其他方向。
-(BOOL)shouldAutorotate{ return NO; } -(NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationLandscapeRight; } -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeRight; }
只需删除那些shouldAutorotate,supportedInterfaceOrientations和preferredInterfaceOrientationForPresentation。
并将此添加到您想要仅显示横向的viewcontroller。
-(void)viewDidAppear:(BOOL)animated{ [[UIDevice currentDevice] setValue: [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeLeft] forKey:@"orientation"]; }
实际上,这是来自类似问题的解决方案。 如何在iOS 8中强制查看控制器方向?
您需要创建一个UIViewController
的子类。 并在此子类中应用与界面方向相关的更改。 扩展要在子类中锁定方向的视图控制器。 我将举一个例子。
我创建的类只显示视图控制器的横向方向。
LandscapeViewController
是UIViewController
的子类,您必须在其中处理方向。
LandscapeViewController.h:
#import @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