不使用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

相關文章
相關標籤/搜索