不使用AutoLayout快速兼容适配iPhone6/6 Plus

 

转载:http://blog.it985.com/5121.htmlphp

声明:本文章是为了后期快速兼容6和6Plus的按比例放大方法,对于部分读者来讲可能以为该方法不妥。可是对于复杂的界面还有急于交付项目的人来讲仍是有必定帮助的。html

如今因为苹果公司出了6和6Plus,让写苹果程序的哥们为了作兼容很头疼。用StoryBoard当然方便,可是后期作兼容要花费太多的时间和精力。
使用AutoLayout虽然会在不一样尺寸的屏幕下自动布局,可是不少东西仍是要本身手动修改,并且使用AutoLayout的话有一个弊病,就是没法经过代码来修改StoryBoard上控件的尺寸和位置。
使用纯代码搭建界面又会以为不够直观,要花时间调整布局,虽然方便后期作调整兼容性,可是影响开发效率。
固然我的以为仍是代码和StoryBoard结合的方式比较方便。
先说下使用本方法的要求,首先iPhone5的界面必定要彻底兼容,这样才能完美兼容6和6Plus。
首先,我么咱们要观察一下5,6和6Plus的尺寸比例关系。发现了他们的关系后呆会作兼容就明白了。
屏幕快照 2014-12-17 下午7.51.08
很明显能看出这三种屏幕的尺寸宽高比是差很少的,所以能够在5的基础上,按比例放大来兼容6和6Plus的屏幕。app

在AppDelegate.h中布局

1
2
@property  float autoSizeScaleX;
@property  float autoSizeScaleY;

在AppDelegate.m中测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度,兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度,兼容性测试
 
- ( BOOL )application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
 
     if (ScreenHeight > 480){
         myDelegate.autoSizeScaleX = ScreenWidth/320;
         myDelegate.autoSizeScaleY = ScreenHeight/568;
     } else {
         myDelegate.autoSizeScaleX = 1.0;
         myDelegate.autoSizeScaleY = 1.0;
     }
}

由于iPhone4s屏幕的高度是480,所以当屏幕尺寸大于iPhone4时,autoSizeScaleX和autoSizeScaleY即为当前屏幕和iPhone5尺寸的宽高比。ui


CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)这个方法使咱们经常使用的设置尺寸的方法,如今我设置了一个相似于这样的方法。

在.m文件中spa

1
2
3
4
5
6
7
8
9
10
11
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake1(100, 100, 50, 50)];
 
CG_INLINE CGRect //注意:这里的代码要放在.m文件最下面的位置
CGRectMake1(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
     AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
     CGRect rect;
     rect.origin.x = x * myDelegate.autoSizeScaleX; rect.origin.y = y * myDelegate.autoSizeScaleY;
     rect.size.width = width * myDelegate.autoSizeScaleX; rect.size.height = height * myDelegate.autoSizeScaleY;
     return rect;
}

这样,这个btn按钮在5,6和6Plus的位置和尺寸比例都是同样的。iPhone6兼容前code

iOS Simulator Screen Shot 2014年12月18日 下午7.07.47

iPhone6兼容后
iOS Simulator Screen Shot 2014年12月18日 下午7.06.38htm

iPhone6Plus兼容前
iOS Simulator Screen Shot 2014年12月18日 下午7.08.29blog

iPhone6Plus兼容后
iOS Simulator Screen Shot 2014年12月18日 下午6.57.07

若是整个项目作完后才开始作兼容的话这个方法的优点就体现出来了,面对几十个工程文件,只需自定义而且替换你的CGRectMake方法,再加上storyBoradAutoLay这个方法就瞬间完成大部分甚至所有的兼容。
其实仍是比较建议用代码和StoryBoard结合的方式来写代码,不管是从作兼容仍是效率来讲都是比较好的。
若是遇到tableView的或者其余的兼容改动,手动调整一下便可。

参考http://www.ui.cn/project.php?id=26980

相关文章
相关标签/搜索