有时候不想用纯代码写页面,用xib拖控件,需要考虑在不同设备上的尺寸和字体适配,比如设计图在iPhone8上控件宽度100,那么在plus机型上如果也是100那就不好看了,因此可以用比例换算w = (screenW / 375) * 100来得到适配好的尺寸,这个方式用纯代码开发没问题,如何应用在xib上呢?
尺寸实配方案:
通过category给NSLayoutConstraint对象添加属性xibSizeFit,重写get和set方法,利用runtime对该属性重新赋值,新值w = (screenW / 375) * 旧值;
具体看如下实现
#import <objc/runtime.h>
@implementation NSLayoutConstraint (Fit)
static void *xibSizeFit_key = &xibSizeFit_key;
- (void)setXibSizeFit:(CGFloat)xibSizeFit {
self.constant = KScaleH(xibSizeFit);
NSLog(@"%f -- %f", xibSizeFit,KScaleH(xibSizeFit));
objc_setAssociatedObject(self, &xibSizeFit_key, @(xibSizeFit), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)xibSizeFit {
return [objc_getAssociatedObject(self, &xibSizeFit_key) floatValue];
}
@end
字体适配方案(原理同上):
#import "UILabel+Fit.h"
#import "Macro.h"
#import <objc/runtime.h>
@implementation UILabel (Fit)
static void *xibFontFit_key = &xibFontFit_key;
- (void)setXibFontFit:(CGFloat)xibFontFit {
self.font = [UIFont fontWithName:self.font.fontName size:KScaleH(xibFontFit)];
objc_setAssociatedObject(self, &xibFontFit_key, @(xibFontFit), OBJC_ASSOCIATION_ASSIGN);
}
- (CGFloat)xibFontFit {
return [objc_getAssociatedObject(self, &xibFontFit_key) floatValue];
}
@end
看下效果