Using the Objective-C Runtime, how do I add the method +layerClass
to the private UIGroupTableViewCellBackground
class (not to its superclass, UIView
)? Note: This is only for testing (to see how UITableViewStyleGrouped
sets cell backgroundView
& selectedBackgroundView
).
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
To dynamically add a class method, instead of an instance method, use object_getClass(cls)
to get the meta class and then add the method to the meta class. E.g.:
UIKIT_STATIC_INLINE Class my_layerClass(id self, SEL _cmd) {
return [MyLayer class];
}
+ (void)initialize {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = object_getClass(NSClassFromString(@"UIGroupTableViewCellBackground"));
NSAssert(class_addMethod(class, @selector(layerClass), (IMP)my_layerClass, "@:@"), nil);
});
}
You might also be able to do this easier by adding the +layerClass
method to a category of UIGroupTableViewCellBackground
and using a forward class definition, i.e. @class UIGroupTableViewCellBackground
, to get it to compile.
回答2:
Try this magic:
+ (void)load {
class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"),
@selector(layerClass), (IMP)my_layerClass, "@:@"), nil);
});
}