XIB的横竖屏适配。有时候我们做一个页面,可能同时需要横竖屏两个方向的适配。我们可以为一个viewcontorller建两个XIB文件。
像这样:
![](https://img.haomeiwen.com/i2641301/c8c3a1f4f38167cf.png)
我们可以在一个里边布局竖屏时显示的控件,另一个里边布局竖屏。竖屏就是我们平常的布局和设置方式了,横屏的XIB文件中要设置为横屏模式:
![](https://img.haomeiwen.com/i2641301/e7d1ba4b2aa39a52.png)
然后你就可以再你的XIB中肆意布置你的控件了。
现在说一下代码。首先,在程序启动的时候是要判断你的设备方向的,所以要在入口方法中加入以下代码:
ViewController *mainVC;
self.window = [UIApplication sharedApplication].windows[0];
self.window.backgroundColor = [UIColor whiteColor];
//获取屏幕方向
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
switch (orientation) {
//判断如果是左右方向就加载横屏的XIB文件
case UIInterfaceOrientationLandscapeLeft:
case UIInterfaceOrientationLandscapeRight:
mainVC = [[ViewController alloc] initWithNibName:@"ViewContorller_L" bundle:[NSBundle mainBundle]];
break;
default:
mainVC = [[ViewController alloc] initWithNibName:@"ViewContorller" bundle:[NSBundle mainBundle]];
break;
}
UINavigationController *navigationController=[[UINavigationController alloc] initWithRootViewController:mainVC];
self.window.rootViewController = navigationController;
[navigationController setNavigationBarHidden:YES animated:NO];
[self.window makeKeyAndVisible];
如果当前的viewcontorller在一个navigationContorller的时候(为什么强调这个看下边)我们需要在viewdidload中添加监听屏幕方向的方法:
- (void)viewDidLoad {
[super viewDidLoad];
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeOrientation) name:UIDeviceOrientationDidChangeNotification object:nil];
}
-(void)changeOrientation {
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
if(orientation==UIDeviceOrientationFaceUp || orientation==UIDeviceOrientationFaceDown
|| orientation == UIDeviceOrientationPortraitUpsideDown)
return;
switch (orientation) {
case UIDeviceOrientationLandscapeLeft:
case UIDeviceOrientationLandscapeRight:
[[NSBundle mainBundle] loadNibNamed:@"ViewContorller_L" owner:self options:nil];
break;
default:
[[NSBundle mainBundle] loadNibNamed:@"ViewContorller" owner:self options:nil];
break;
}
此地有坑要注意了!
如果当前的viewcontorller没有在navigationContorller中时你就还得将以下两个方法加入通知中心,因为他们有可能不被自动调用
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
他们不被调用的后果就是当横竖屏切换时横屏或者竖屏XIB中的view.bounds没有随着屏幕的旋转而改变,简单来说就是竖屏转横屏时屏幕旋转了XIB也切换了但是它的VIEW仍然是竖屏的,所以会出现部分黑框导致不正常显示。
此时基本就完成了横竖屏的自适应啦!不过如果你的控件需要显示某些东西的时候,你就不得不在上文中的changeOrientation方法中去刷你的控件了,即每次旋转屏幕切换XIB时都需要刷新。
网友评论