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
).
The normal way to add functionality (methods) to a class in Python is to define functions in the class body. There are many other ways to accomplish this that can be useful in different situations. The method can also be defined outside the scope of the class.
The __new__() is a static method of the object class. When you create a new object by calling the class, Python calls the __new__() method to create the object first and then calls the __init__() method to initialize the object's attributes.
Python Code can be dynamically imported and classes can be dynamically created at run-time. Classes can be dynamically created using the type() function in Python. The type() function is used to return the type of the object. The above syntax returns the type of object.
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.
Try this magic:
#include <objc/runtime.h>
+ (void)load {
class_addMethod(objc_getMetaClass("UIGroupTableViewCellBackground"),
@selector(layerClass), (IMP)my_layerClass, "@:@");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With