问题
UIColor has color methods such as blackColor, whiteColor and so on. I would like to get a color list of them like:['blackColor','whiteColor'...]. But after checking the method_list, ivar_list and property_list, I find no color method in the lists. The code is written in Swift as following:
//: Playground - noun: a place where people can play
import UIKit
var ivarCount: UInt32 = 0
var propertyCount: UInt32 = 0
var methodCount: UInt32 = 0
let ivars = class_copyIvarList(UIColor.self, &ivarCount)
let properties = class_copyPropertyList(UIColor.self, &propertyCount)
let methods = class_copyMethodList(UIColor.self, &methodCount)
var ivarNames: [String] = []
var propertyNames: [String] = []
var methodNames: [String] = []
for var i = 0; i < Int(ivarCount); ++i {
let ivar = ivars[i]
let name = ivar_getName(ivar)
ivarNames.append(String.fromCString(name)!);
}
for var i = 0; i < Int(propertyCount); ++i {
let p = properties[i]
let name = property_getName(p)
propertyNames.append(String.fromCString(name)!)
}
for var i = 0; i < Int(methodCount); ++i {
let m = methods[i]
let name = sel_getName(method_getName(m))
methodNames.append(String.fromCString(name)!)
}
NSLog("ivars:%@",ivarNames)
NSLog("properties:%@", propertyNames)
NSLog("methods:%@", methodNames)
The result is as following:
2016-01-18 11:26:25.531 MyPlayground[42239:4975071] ivar:(
"_systemColorName"
)
2016-01-18 11:26:25.531 MyPlayground[42239:4975071] properties:(
CGColor,
CIColor,
systemColorName
)
2016-01-18 11:26:25.532 MyPlayground[42239:4975071] method:(
"initWithColorLiteralRed:green:blue:alpha:",
classForCoder,
hash,
"isEqual:",
set,
"initWithHue:saturation:brightness:alpha:",
"_getWhite:alpha:",
"_systemColorName",
"initWithWhite:alpha:",
"_getRed:green:blue:alpha:",
"_colorBlendedWithColor:",
styleString,
isPatternColor,
"getHue:saturation:brightness:alpha:",
CIColor,
"initWithPatternImage:",
"_setSystemColorName:",
"_luminance",
"_colorBlendedWithColor:compositingFilter:",
"_isSimilarToColor:withinPercentage:",
"_colorDifferenceFromColor:",
"_luminanceDifferenceFromColor:",
"_colorBlendedWithColors:",
dealloc,
"copyWithZone:",
"encodeWithCoder:",
"initWithCoder:",
cgColor,
"initWithCGColor:",
"initWithRed:green:blue:alpha:",
CGColor,
"getRed:green:blue:alpha:",
setFill,
"colorWithAlphaComponent:",
setStroke,
alphaComponent,
"getWhite:alpha:",
"initWithCIColor:"
)
回答1:
That's because the color methods are class methods, which are bound to UIColor's metaclass. And class_copyMethodList returns the instance methods of the class passed as argument.
You can obtain the metaclass by calling object_getClass() on UIColor, so you'll need to change only one line to get all class methods of UIColor:
let methods = class_copyMethodList(object_getClass(UIColor.self), &methodCount)
object_getClass() works on Class values as in Objective-C every class has an isa pointer, which qualifies it for being an object.
来源:https://stackoverflow.com/questions/34846964/how-to-get-all-color-methods-of-uicolor