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

 

 

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中多次調用和使用,節省代碼量。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM