你如何在Swift中调用这样的Objective-C类别方法?
+(UIColor*)colorWithHexString:(NSString*)hex alpha:(float)alpha;
The compiler automatically looks for common ObjC naming patterns and substitutes Swift patterns in their place. An ObjC class method that returns an instance of the class (and is named a certain way, it looks like) gets turned into a Swift convenience initializer.
If you have the ObjC method (defined by a custom category):
+ (UIColor *)colorWithHexString:(NSString *)hex alpha:(float)alpha;
The compiler generates the Swift declaration:
convenience init(hexString: String?, alpha: CFloat)
And you call it like this:
let color = UIColor(hexString: "#ffffff", alpha: 1.0)
And in Swift 2.0 or later, you can use the NS_SWIFT_NAME
macro to make ObjC factory methods that don't match the naming pattern import to Swift as initializers. eg:
@interface UIColor(Hex)
+ (UIColor *)hexColorWithString:(NSString *)string
NS_SWIFT_NAME(init(hexString:));
@end
// imports as
extension UIColor {
init(hexString: String)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.