iOS 屏幕比例縮放 ScaleLayout

ScaleLayout.h


//
//  ScaleLayout.h
//  ScaleLayout
//
//  Created by 黃健 on 16/7/26.
//  Copyright © 2016年 黃健. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UILabel (ScaleLayout)
@end

@interface UIButton (ScaleLayout)
@end

@interface NSLayoutConstraint (ScaleLayout)
@end

ScaleLayout.m


//
//  ScaleLayout.m
//  ScaleLayout
//
//  Created by 黃健 on 16/7/26.
//  Copyright © 2016年 黃健. All rights reserved.
//

#import "ScaleLayout.h"
#import <objc/runtime.h>

#define screenW [UIScreen mainScreen].bounds.size.width
#define screenH [UIScreen mainScreen].bounds.size.height

// 已iPhone 5尺寸爲標本
#define wScale  ((screenW > 320.f) ? screenW / 320.f : 1)

@implementation UILabel (ScaleLayout)

+ (void)load
{
    Method imp    = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method hj_imp = class_getInstanceMethod([self class], @selector(hj_initWithCoder:));
    method_exchangeImplementations(imp, hj_imp);
}

- (id)hj_initWithCoder:(NSCoder*)aDecoder
{
    [self hj_initWithCoder:aDecoder];

    if (self)
    {
        if(self.tag != 999999)
        {
            self.font = [UIFont systemFontOfSize:self.font.pointSize * wScale];
        }
    }
    return self;
}

@end


@implementation UIButton (ScaleLayout)

+ (void)load
{
    Method imp    = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method hj_imp = class_getInstanceMethod([self class], @selector(hj_initWithCoder:));
    method_exchangeImplementations(imp, hj_imp);
}

- (id)hj_initWithCoder:(NSCoder*)aDecoder
{
    [self hj_initWithCoder:aDecoder];

    if (self)
    {
        if(self.titleLabel.tag != 999999)
        {
            self.titleLabel.font = [UIFont systemFontOfSize:self.titleLabel.font.pointSize * wScale];
        }
    }
    return self;
}

@end

@implementation NSLayoutConstraint (ScaleLayout)

+ (void)load
{
    Method imp    = class_getInstanceMethod([self class], @selector(initWithCoder:));
    Method hj_imp = class_getInstanceMethod([self class], @selector(hj_initWithCoder:));
    method_exchangeImplementations(imp, hj_imp);
}

- (id)hj_initWithCoder:(NSCoder*)aDecoder
{
    [self hj_initWithCoder:aDecoder];

    if (self)
    {
        self.constant *= wScale;
    }
    return self;
}

@end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章