iOS -不同模拟器字体适配

本文介绍了一种自定义UILabel字体缩放的方法,通过创建UILabel的分类并利用Objective-C运行时的功能来修改UILabel的初始化方法,实现不同屏幕尺寸下字体大小的自动调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.先建立一个UILabel的分类

导入#import <objc/runtime.h>头文件

2.在.m文件中写入如下代码

//不同设备的屏幕比例(当然倍数可以自己控制)

#define IPHONE_HEIGHT  [UIScreen mainScreen].bounds.size.height

#define SizeScale ((IPHONE_HEIGHT > 568) ? IPHONE_HEIGHT/568 : 1)

@implementation UILabel(myFont)

 

+ (void)load{

    Method imp = class_getInstanceMethod([self class], @selector(initWithCoder:));

    Method myImp = class_getInstanceMethod([self class], @selector(myInitWithCoder:));

    method_exchangeImplementations(imp, myImp);

    

    Method cmp = class_getInstanceMethod([self class], @selector(initWithFrame:));

    Method myCmp = class_getInstanceMethod([self class], @selector(myInitWithFrame:));

    method_exchangeImplementations(cmp, myCmp);

}

 

- (id)myInitWithCoder:(NSCoder*)aDecode{

    [self myInitWithCoder:aDecode];

    if (self) {

        //部分不像改变字体的 把tag值设置成333跳过

        if(self.tag != 333){

            CGFloat fontSize = self.font.pointSize;

            self.font = [UIFont systemFontOfSize:fontSize * SizeScale];

             NSLog(@" label的大小 == %f", self.font.pointSize);

        }

    }

    return self;

}

 

- (id)myInitWithFrame:(CGRect)frame{

    [self myInitWithFrame:frame];

    if(self){

        CGFloat fontSize = self.font.pointSize;

        self.font = [UIFont systemFontOfSize:fontSize * SizeScale];

        NSLog(@" label的大小 == %f", self.font.pointSize);

    }

    return self;

}

 

 

@end

 

3.在调用文件中导入分类

#import "ViewController.h"

#import "UIButton+myFont.h"

 

@interface ViewController ()

 

/*注释*/

@property (nonatomic,strong)UILabel *label;

 

@end

 

@implementation ViewController

 

- (void)viewDidLoad {

    [super viewDidLoad];

    [self.view addSubview:self.label];

    // Do any additional setup after loading the view, typically from a nib.

    

}

 

- (void)viewWillAppear:(BOOL)animated

{

    NSLog(@"%@",self.label.font);

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

 

- (UILabel *)label{

    if (!_label) {

      

        _label = [[UILabel alloc]initWithFrame:CGRectMake(50, 100, 100, 30)];

//        _label.font = [UIFont systemFontOfSize:17];

        _label.tag = 32;

        _label.text = @"这是测试文字";

    }

    return _label;

}

 

@end

 

转载于:https://www.cnblogs.com/huiyi-520/p/6272916.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值