应用中有时会有需求统一的label字体和字号大小等等一系列要求且与默认不符合的话,而大量的控件每次设置又比较浪费,可以用runtime做统一修改,最实用的是应用在大型项目中突接需求整体修改属性时,下面直接上代码:
#import "UILabel+changeDefaults.h"
#import
@implementationUILabel (changeDefaults)
+ (void)load
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Classclass = [selfclass];
SELoriginalSelector =@selector(init);
SELoriginalSelector2 =@selector(initWithFrame:);
SELoriginalSelector3 =@selector(awakeFromNib);
SELswizzledSelector =@selector(ZWJBaseInit);
SELswizzledSelector2 =@selector(ZWJBaseInitWithFrame:);
SELswizzledSelector3 =@selector(ZWJBaseAwakeFromNib);
MethodoriginalMethod =class_getInstanceMethod(class, originalSelector);
MethodoriginalMethod2 =class_getInstanceMethod(class, originalSelector2);
MethodoriginalMethod3 =class_getInstanceMethod(class, originalSelector3);
MethodswizzledMethod =class_getInstanceMethod(class, swizzledSelector);
MethodswizzledMethod2 =class_getInstanceMethod(class, swizzledSelector2);
MethodswizzledMethod3 =class_getInstanceMethod(class, swizzledSelector3);
BOOLdidAddMethod =class_addMethod(class, originalSelector,method_getImplementation(swizzledMethod),method_getTypeEncoding(swizzledMethod));
BOOLdidAddMethod2 =class_addMethod(class, originalSelector2,method_getImplementation(swizzledMethod2),method_getTypeEncoding(swizzledMethod2));
BOOLdidAddMethod3 =class_addMethod(class, originalSelector3,method_getImplementation(swizzledMethod3),method_getTypeEncoding(swizzledMethod3));
if(didAddMethod) {
class_replaceMethod(class, swizzledSelector,method_getImplementation(originalMethod),method_getTypeEncoding(originalMethod));
}
else
{
method_exchangeImplementations(originalMethod, swizzledMethod);
}
if(didAddMethod2) {
class_replaceMethod(class, swizzledSelector2,method_getImplementation(originalMethod2),method_getTypeEncoding(originalMethod2));
}
else
{
method_exchangeImplementations(originalMethod2, swizzledMethod2);
}
if(didAddMethod3) {
class_replaceMethod(class, swizzledSelector3,method_getImplementation(originalMethod3),method_getTypeEncoding(originalMethod3));
}
else
{
method_exchangeImplementations(originalMethod3, swizzledMethod3);
}
});
}
- (instancetype)ZWJBaseInit
{
id__self= [self ZWJBaseInit];
UIFont *font = [UIFont fontWithName:@"PingFangTC-Regular" size:12];
if(font) {
self.font= font;
self.textAlignment = NSTextAlignmentCenter;
//另修改属性可在此加...
}
return__self;
}
- (instancetype)ZWJBaseInitWithFrame:(CGRect)rect
{
id __self = [self ZWJBaseInitWithFrame:rect];
UIFont *font = [UIFont fontWithName:@"PingFangTC-Regular" size:12];
if(font) {
self.font= font;
self.textAlignment = NSTextAlignmentCenter;
//另修改属性可在此加...
}
return__self;
}
- (void)ZWJBaseAwakeFromNib
{
[self ZWJBaseAwakeFromNib];
UIFont *font = [UIFont fontWithName:@"PingFangTC-Regular" size:12];
if(font) {
self.font= font;
self.textAlignment = NSTextAlignmentCenter;
//另修改属性可在此加...
}
}
@end