对于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任意尺寸上用了。赶快试试吧!
注意:此方法只适用于精度不是要求高的应用;