在手机开发过程中,你可能会需要你的手机横过来看,有可能是全部界面都要横过来,有可能是当用户把手机横过来的时候,你的界面也想让他横过来,也有可能是只有部分界面需要横着显示的,根据不同的情况,有不同的解决办法。
首先,我们要理清,方向分两种,一种是设备的方向,一种是视图方向。设备方向有两种方式可以改变,一个是通过重力加速计,即旋转屏幕的方式去改变,一个是通过代码,调用UIDevice的方式去改变!直接设置 UIDevice 的 orientation,但是这种方式不推荐,上传appStore有被拒的风险。
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
[[UIDevice currentDevice] performSelector:@selector(setOrientation:) withObject:(id)UIInterfaceOrientationPortrait];
}
我们都是通过改变视图的方向来让屏幕旋转的。
情景一:程序中所有界面都是横屏显示的
解决办法:修改工程配置文件plist,里面的UISupportedInterfaceOrientations属性表示程序支持的方向,我们把它改成只支持Left和Right
UISupportedInterfaceOrientations
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight
UIInterfaceOrientationPortrait表示Home键按钮的方向,也就是竖屏方向,不要他
这样,程序启动的时候就是横屏显示了,当然你需要使用横屏的插件来设计界面了,可以使用
UIApplication *application=[UIApplication sharedApplication];
[application setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
application.keyWindow.transform=CGAffineTransformMakeRotation(M_PI);
注:需要设置程序不会自动响应自动旋转
//因为想要手动旋转,所以先关闭自动旋转
- (BOOL)shouldAutorotate{
return NO;
}
//因为想要手动旋转,所以先关闭自动旋转
- (BOOL)shouldAutorotate{
return NO;
}
然后就是实现旋转的代码了,我们使用的是假旋转,并没有改变 UIDevice 的 orientation,而是改变某个view的 transform,利用 CGAffineTransformMakeRotation 来达到目的
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//实例化chart
cv =[[ChartViewBase alloc] initWithFrame:CGRectMake(0, 0, 320, 240)];
[self.view addSubview:cv];
//旋转屏幕,但是只旋转当前的View
[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
CGRect frame = [UIScreen mainScreen].applicationFrame;
self.view.bounds = CGRectMake(0, 0, frame.size.height, 320);
}
注意:
- (BOOL)shouldAutorotate;
- (NSUInteger)supportedInterfaceOrientations;
UIViewController *viewCtrl = [[UIViewController alloc] init];
UINavigationController *navCtrl = [[UINavigationController alloc] initWithRootViewController:viewCtrl];
if ([window respondsToSelector:@selector(setRootViewController:)]) {
self.window.rootViewController = navCtrl;
} else {
[self.window addSubview:navCtrl.view];
}
-(NSUInteger)supportedInterfaceOrientations{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate{
return YES;
}