iOS 字体大小适配

iOS 字体大小适配
1、用宏定义适配字体大小(根据屏幕尺寸判断)
(1)方法

//宏定义
#define SCREEN_WIDTH ([UIScreen mainScreen].bounds.size.width)
#define FONT_SIZE(size) ([UIFont systemFontOfSize:FontSize(size))

/**
 *  字体适配 我在PCH文件定义了一个方法
 */
static inline CGFloat FontSize(CGFloat fontSize){
    if (SCREEN_WIDTH==320) {
        return fontSize-2;
    }else if (SCREEN_WIDTH==375){
        return fontSize;
    }else{
        return fontSize+2;
    }
}

(2)方法

#define IsIphone6P          SCREEN_WIDTH==414
#define SizeScale           (IsIphone6P ? 1.5 : 1)
#define kFontSize(value)    value*SizeScale
#define kFont(value)        [UIFont systemFontOfSize:value*SizeScale]

2、利用runtime给UIFont写分类 替换系统自带的方法

   #define MyUIScreen  375 // UI设计原型图的手机尺寸宽度
    UIFont+runtime.m
    
    #import "UIFont+runtime.h"
    #import 
    
    @implementation UIFont (runtime)
    
    + (void)load {
        // 获取替换后的类方法
        Method newMethod = class_getClassMethod([self class], @selector(adjustFont:));
        // 获取替换前的类方法
        Method method = class_getClassMethod([self class], @selector(systemFontOfSize:));
        // 然后交换类方法,交换两个方法的IMP指针,(IMP代表了方法的具体的实现)
        method_exchangeImplementations(newMethod, method);
    }
    
    + (UIFont *)adjustFont:(CGFloat)fontSize {
        UIFont *newFont = nil;
        newFont = [UIFont adjustFont:fontSize * [UIScreen mainScreen].bounds.size.width/MyUIScreen];
        return newFont;
    }
    @end

// 实现
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 60)];
    label.text = @"iOS字体大小适配";
    label.font = [UIFont systemFontOfSize:16];
    [self.view addSubview:label];

猜你喜欢

转载自blog.csdn.net/heqiang2015/article/details/84134208
今日推荐