很多時(shí)候我們會(huì)使用Xib開發(fā)界面,如果是Xib創(chuàng)建的,我們?cè)偃ッ總€(gè)控件都重新都設(shè)置一遍字體,豈不是無端增加工作量,最好的辦法是在XIB里面設(shè)置字體大小后自動(dòng)進(jìn)行等比縮放。
我的思路是這樣的,通過Xib創(chuàng)建的視圖在初始化的時(shí)候都會(huì)調(diào)用awakeFromNib方法,通過交換方法,實(shí)現(xiàn)為Xib適配字體。
+ (void)load {
Method swizeeMethod = class_getInstanceMethod([UILabel class], @selector(d_awakeFromNib));
Method originalMethod = class_getInstanceMethod([UILabel class], @selector(awakeFromNib));
if (!class_addMethod([UILabel class], @selector(awakeFromNib), method_getImplementation(swizeeMethod), method_getTypeEncoding(swizeeMethod))) {
method_exchangeImplementations(originalMethod,swizeeMethod);
} else {
class_replaceMethod(self, @selector(d_awakeFromNib), method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
}
}
- (void)d_awakeFromNib {
self.font = [UIFont fontWithDescriptor:self.font.fontDescriptor size:self.font.pointSize * [self getScaleFontSize]];
[self d_awakeFromNib];
}
+ (CGFloat)getScaleFontSize{
// 375 是設(shè)計(jì)師一般都習(xí)慣以iphone6設(shè)計(jì)UI
CGFloat width = [[UIScreen mainScreen] currentMode].size.width;
// 1242是iPhone XS Max的寬度商虐,如果不加限制在iPad字體慘不忍睹,大于iPhone XS Max 的都適配1.5倍
if (width <= 1242) {
return [UIScreen mainScreen].bounds.size.width/375;
}
else{
return 1.5;
}
}