纯代码 适配 iPhone 6 (+)

来源:互联网 发布:周末网络国债理财机构 编辑:程序博客网 时间:2024/06/05 12:49

在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尺寸的宽高比。比如,
如果是5,autoSizeScaleX=1,autoSizeScaleY=1;
如果是6,autoSizeScaleX=1.171875,autoSizeScaleY=1.17429577;
如果是6Plus,autoSizeScaleX=1.29375,autoSizeScaleY=1.2957;
现在我们获取了比例关系后,先来看一下如何解决代码设置界面时的适配。
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)这个方法使我们常用的设置尺寸的方法,现在我设置了一个类似于这样的方法。
在.m文件中

1

2

3

4

5

6

7

8

9

10

11

UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake1(100, 100, 50, 50)];

 

CG_INLINE CGRect

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的位置和尺寸比例都是一样的。


如果整个项目做完后才开始做适配的话这个方法的优势就体现出来了,面对几十个工程文件,只需自定义并且替换你的CGRectMake方法,再加上storyBoradAutoLay这个方法就瞬间完成大部分甚至全部的适配,如果遇到tableView的或者其他的手动调整一下即可。

0 0
原创粉丝点击