20

iOS字体大小适配的几种方法

 5 years ago
source link: http://www.cocoachina.com/ios/20181115/25481.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在iOS开发中,有些公司对字体也有适配要求,为了让字体美观,所以在不同尺寸的屏幕上字体大小也要做到适配。

自己总结了几种方法供大家参考。

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

//宏定义
#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;
    }
}

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

1.5代表6P尺寸的时候字体为1.5倍,5S和6尺寸时大小一样,也可根据需求自定义比例。

代码如下:

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

方法三:(利用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

@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

外部正常调用系统设置字体方法就行

Controller类中正常调用就行了:

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];

注意:

load方法只会走一次,利用runtime的method进行方法的替换

替换的方法里面(把系统的方法替换成我们自己写的方法),这里要记住写自己的方法,不然会死循环

之后凡是用到systemFontOfSize方法的地方,都会被替换成我们自己的方法,即可改字体大小了

注意:此方法只能替换 纯代码 写的控件字号,如果你用xib创建的控件且在xib里面设置的字号,那么替换不了!你需要在xib的

awakeFromNib方法里面手动设置下控件字体

作者:深蓝_S

链接:https://www.jianshu.com/p/7a6106f952d3


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK