事出有因
一般情況下,設(shè)計給出的圖都是按照6的屏幕大小來做的,并且他們還希望我們做出來的樣子在所有的屏幕上展示的都一樣,這樣就需要等比例適配了
代碼創(chuàng)建的怎么解決
如果是代碼創(chuàng)建的,我們可以通過一個宏定義解決
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define font(R) (R)*(kScreenWidth)/375
kScreenWidth
是獲取的屏幕寬度,通過屏幕比例計算,來得到最終的字體大小,使用起來也比較方便
label.font = [UIFont systemFontOfSize:font(12)];
XIB如何做
如果是XIB
創(chuàng)建的,我們再去這樣每個都重新都設(shè)置一遍字體,豈不是無端增加工作量,最好的辦法是在XIB
里面設(shè)置字體大小后自動進行等比縮放.
我的思路是這樣的,通過XIB
創(chuàng)建的視圖在初始化的時候都會調(diào)用awakeFromNib
方法,通過交換方法,實現(xiàn)為awakeFromNib
方法增加下面的這一行代碼
#define WJXScaleAdapter ((CGFloat)(WJXSCREEN_WIDTH / 375.0))
//-----------
self.font = [UIFont fontWithDescriptor:self.font.fontDescriptor size:self.font.pointSize * WJXScaleAdapter];
self.font.fontDescriptor
可以得到當前字體的樣式,只改變大小,不能改變字體的樣式
完整代碼
定義一個 category 實現(xiàn)以下代碼
@implementation UILabel (TMLayoutFont)
// 在load方法中實現(xiàn)讓 jx_awakeFromNib 和 awakeFromNib 方法交換 不明白的可以搜索下 ios 方法交換
+ (void)load {
Method method3 = class_getInstanceMethod([UILabel class], @selector(jx_awakeFromNib));
Method method4 = class_getInstanceMethod([UILabel class], @selector(awakeFromNib));
if (!class_addMethod([UILabel class], @selector(awakeFromNib), method_getImplementation(method3), method_getTypeEncoding(method3))) {
method_exchangeImplementations(method4, method3);
} else {
class_replaceMethod(self, @selector(jx_awakeFromNib), method_getImplementation(method4), method_getTypeEncoding(method4));
}
}
// 方法交換以后 當系統(tǒng)調(diào)用 awakeFromNib 方法的時候?qū)嶋H上會調(diào)用 jx_awakeFromNib 方法
- (void)jx_awakeFromNib {
[self jx_awakeFromNib];
self.font = [UIFont fontWithDescriptor:self.font.fontDescriptor size:self.font.pointSize * WJXScaleAdapter];
}
除了UILabel
外 對其他可以設(shè)置字體的控件也有效,方法相同