您的位置:首页 > 移动开发 > Objective-C

ios中object c纯代码开发屏幕适配处理方法

2016-06-01 20:24 441 查看


原文链接


ios中object c纯代码开发屏幕适配处理方法

纯代码开发屏幕适配处理方法:
为适配iphone各个版本的机型,对ui布局中的坐标采用比例的方式进行初始化,在这里选定iphone6作为ui布局
1.首先在AppDelegate.h中定义两个属性:

1 #import <UIKit/UIKit.h>
2
3 @interface AppDelegate : UIResponder <UIApplicationDelegate>
4
5 @property (strong, nonatomic) UIWindow *window;
6
7
8 @property(nonatomic,assign)CGFloat autoSizeScaleX;
9 @property(nonatomic,assign)CGFloat autoSizeScaleY;
10
11 @end


 
 
cdcb
2.在AppDelegate.m中对属性进行初始化(计算出当前运行的iphone版本的屏幕尺寸跟设计ui时选定的iphone6的比例):
 

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.

self.autoSizeScaleX = [UIScreen mainScreen].bounds.size.width/375;
self.autoSizeScaleY = [UIScreen mainScreen].bounds.size.height/667;

return YES;
}@end


 
3.在需要使用ui布局的地方,用内联函数进行数据初始化(内联函数会在程序编译的时候执行,这样做的好处是加快程序在运行时候的速度,在运行的时候就不需要再对坐标进  行计算):
 

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setTitle:@"登陆" forState:UIControlStateNormal];
[btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
btn.frame = CGRectMake1(20, 20, 335, 300);
btn.backgroundColor = [UIColor greenColor];
[self.view addSubview:btn];
}

//创建内联函数 (在程序编译的时候执行,在函数前声明后编译器执行起来更具效率,使宏的定义更节省,不涉及栈的操作)
CG_INLINE CGRect
CGRectMake1(CGFloat x,CGFloat y,CGFloat width,CGFloat height)
{
//创建appDelegate 在这不会产生类的对象,(不存在引起循环引用的问题)
AppDelegate *app = [UIApplication sharedApplication].delegate;

//计算返回
return CGRectMake(x * app.autoSizeScaleX, y * app.autoSizeScaleY, width * app.autoSizeScaleX, height * app.autoSizeScaleY);
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}

@end


 
4.进阶:把内联函数些到一个viewController中,然后把这个viewController作为其他viewController的父类,这样做的话可以只写一个内联函数,然后在别的viewController中多次调用和使用,节省代码量。
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: