iOS 字体大小适配

来源:互联网 发布:淘宝商品背景素材 编辑:程序博客网 时间:2024/05/29 16:36

方式一:用宏定义适配字体大小 (根据屏幕尺寸判断)

方法一

#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;    }}

方法二

// 如果6和5s尺寸时字体大小一样,为1倍,6P尺寸的时候字体的大小为1.5倍,那么可有如下定义(可根据需求自定义比例)#define IsIphone6P          SCREEN_WIDTH==414#define SizeScale           (IsIphone6P ? 1.5 : 1)#define kFontSize(value)    value*SizeScale#define kFont(value)        [UIFont systemFontOfSize:kFontSize(value)]

方式二:利用runTime给UIFont写类别 替换系统自带的方法,推荐使用这种

class_getInstanceMethod 获取实例方法class_getClassMethod 获取类方法1. 首先需要创建一个UIFont的类别2. 自己UI设计原型图的手机尺寸宽度#define MyUIScreen  375 // UI设计原型图的手机尺寸宽度(6), 6p的--414
具体实现
UIFont+runtime.m#import "UIFont+runtime.h"#import <objc/runtime.h>@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(50, 100, 100, 50)];label.text = @"iOS字体大小适配";label.font = [UIFont systemFontOfSize:17];[self.view addSubview: label];

注意:
1. 替换的方法里面(把系统的方法替换成我们自己写的方法),要调用我们自己的方法( [UIFont adjustFont:xxxx]),不然会造成死循环。
2. 此方法只能替换 纯代码 写的控件字号,如果用xib创建的控件且在xib里面设置的字号,那么无法实现替换!需要在xib的
awakeFromNib方法里面手动设置下控件字体。