iOS 屏幕適配

對於iOS開發,屏幕的適配真的很重要,在這裏就很少說了,今天主要給你們介紹一下按比例適配;app

1.首先咱們在 AppDelegate.h 裏面定義兩個宏定義,屏幕的寬和高iphone

#import <UIKit/UIKit.h>ide

//宏定義函數

#define ScreenHEIGHT [[UIScreen mainScreen] bounds].size.heightatom

#define ScreenWIDTH  [[UIScreen mainScreen] bounds].size.widthspa

 @interface AppDelegate : UIResponder <UIApplicationDelegate>代理

@property (strong, nonatomic) UIWindow *window;ip

//設置自動縮放的比例開發

@property (nonatomic ,assign) float autoSizeScaleX;it

@property (nonatomic ,assign) float autoSizeScaleY;

 @end

 2.在AppDelegate.m文件裏面實現了計算縮放屏幕的的倍數:

#import "AppDelegate.h"

 @interface AppDelegate ()

 @end

@implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    //建立一個UIApplication的單例,而且指定代理,這樣就能夠傳值了

    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];

    //判斷屏幕的高度若是 大於480 ,注意這裏是以5s爲基準

    if (ScreenHEIGHT >480) {

        //計算出自動縮放的倍數

        myDelegate.autoSizeScaleX = ScreenWIDTH/320;

        myDelegate.autoSizeScaleY = ScreenHEIGHT/568;

    }

    else{

        //小於480 就是iPhoneon4,因此正常顯示

        myDelegate.autoSizeScaleX = 1.0;

        myDelegate.autoSizeScaleY = 1.0;

    }

    return YES;

}

 3.在要屏幕適配的頁面加上一個 CG_INLINE CGRect(內聯函數):

#import "ViewController.h"

#import "AppDelegate.h"

@interface ViewController ()

 @end

 @implementation ViewController

 - (void)viewDidLoad {

    [super viewDidLoad];

    }

 

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

//內聯函數

CG_INLINE CGRect

// 從新定義控件的尺寸

   CGRentMake1(CGFloat x, CGFloat y, CGFloat width, CGFloat height){

       CGRect rect;

       AppDelegate *myappdelegate = [[UIApplication sharedApplication] delegate];

       //按比例縮放 座標,和尺寸

       rect.origin.x = x*myappdelegate.autoSizeScaleX;

       rect.origin.y = y*myappdelegate.autoSizeScaleY;

       rect.size.width = width*myappdelegate.autoSizeScaleX;

       rect.size.height = width*myappdelegate.autoSizeScaleY;

       return rect;

}

@end

 4.寫完內聯函數後,之後你定義的控件的frame 都不要用CGRectMake來設置尺寸了,用從新定義控件的CGRentMake1來設置,這樣就實現了自動縮放了,能夠任性在

iphone任意尺寸上用了。趕快試試吧!

 注意:此方法只適用於精度不是要求高的應用;

相關文章
相關標籤/搜索