1. 程式人生 > >iOS字型根據不同螢幕尺寸適配

iOS字型根據不同螢幕尺寸適配

因為檢視使用storyboard 和 XIB拖拽進來了,如果需要對不同大小的螢幕進行Font 字型適配的話可以使用分類。

在load 方法中 利用OC的執行時機制,對所有的 UIButton 、UILabel 做處理。

關鍵程式碼:

UIButton 按鈕的處理方式 

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

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

    [self myInitWithCoder:aDecode];
    if (self) {
        // 部分不想改變字型的 把tag值設定成555跳過
        if (self.titleLabel.tag != 555) {
            CGFloat fontSize = self.titleLabel.font.pointSize;
            self.titleLabel.font = [UIFont systemFontOfSize:fontSize * SizeScale];
        }
    }
    return self;
}

UILabel 的處理方式

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

- (id)myInitWithCoder:(NSCoder *)aDecode{
    
    [self myInitWithCoder:aDecode];
    if (self) {
        // 部分不想改變字型的 把tag值設定成555跳過
        if (self.tag != 555) {
            CGFloat fontSize = self.font.pointSize;
            self.font = [UIFont systemFontOfSize:fontSize * SizeScale];
        }
    }
    return self;
}



Demo下載地址:https://github.com/xiangxianxiao/XXFontAdaptation