美文网首页iOS Developer
使用XIB做横竖屏自适应

使用XIB做横竖屏自适应

作者: 在海边的人 | 来源:发表于2016-08-26 22:22 被阅读2385次

    XIB的横竖屏适配。有时候我们做一个页面,可能同时需要横竖屏两个方向的适配。我们可以为一个viewcontorller建两个XIB文件。

  像这样:


我们可以在一个里边布局竖屏时显示的控件,另一个里边布局竖屏。竖屏就是我们平常的布局和设置方式了,横屏的XIB文件中要设置为横屏模式:

然后你就可以再你的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时都需要刷新。

相关文章

网友评论

    本文标题:使用XIB做横竖屏自适应

    本文链接:https://www.haomeiwen.com/subject/dsmzsttx.html