Apple’s official classes only provide a small number of member variables and methods, but sometimes we don’t provide them, which can be very frustrating for developers. How do you get all the variables and methods in a class to see if there are any corresponding variables and methods? We can use apple’s built-in runtime to get this
The Runtime (Runtime) :
- Apple’s official C language library
- Can do a lot of low-level operations (such as accessing some hidden member variables \ member methods….)
The following uses UITextField as an example
Contains runtime header files
#import <objc/runtime.h>
Copy the code
Get all member variables
unsigned int count = 0;
// Copy out the list of member variables
Ivar *ivars = class_copyIvarList([UITextField class], &count);
for (int i = 0; i<count; i++) {
// Fetch member variables
Ivar ivar = *(ivars + i);
// Prints the member variable name
LXFLog(@"%s", ivar_getName(ivar));
// Prints the data type of the member variable
LXFLog(@"%s", ivar_getTypeEncoding(ivar));
}
/ / release
free(ivars);
Copy the code
Swift is written as follows
var count: UInt32 = 0
let ivars = class_copyIvarList(UIViewController.self, &count)!
for i in 0..<count {
let namePoint = ivar_getName(ivars[Int(i)])!
let name = String(cString: namePoint)
print(name)
}
Copy the code
Get all member methods
// Change the UITextField below to the name of the class where you want to get all the attributes
unsigned int methCount = 0;
Method *meths = class_copyMethodList([UITextField class], &methCount);
for(int i = 0; i < methCount; i++) {
Method meth = meths[i];
SEL sel = method_getName(meth);
const char *name = sel_getName(sel);
NSLog(@"%s", name);
}
free(meths);
Copy the code
Finally, assign values to corresponding member variables via KVC. Such as:
// Change the dot text color
UILabel *placeholderLabel = [self valueForKeyPath:@"_placeholderLabel"];
placeholderLabel.textColor = [UIColor redColor];
// Or so
[self setValue:[UIColor grayColor] forKeyPath:@"_placeholderLabel.textColor"];
Copy the code