如何在Swift中调用Objective-C类别方法

时间:2023-01-15 14:11:19

How would you call an Objective-C category method like this in Swift?

你如何在Swift中调用这样的Objective-C类别方法?

+(UIColor*)colorWithHexString:(NSString*)hex alpha:(float)alpha;

1 个解决方案

#1


15  

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.

编译器自动查找常见的ObjC命名模式,并在其位置替换Swift模式。一个ObjC类方法返回一个类的实例(并以某种方式命名,看起来像)被转换为Swift便利初始化器。

If you have the ObjC method (defined by a custom category):

如果您有ObjC方法(由自定义类别定义):

 + (UIColor *)colorWithHexString:(NSString *)hex alpha:(float)alpha;

The compiler generates the Swift declaration:

编译器生成Swift声明:

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. e.g.:

在Swift 2.0或更高版本中,您可以使用NS_SWIFT_NAME宏将ObjC工厂方法与作为初始化程序的Swift的命名模式导入不匹配。例如。:

@interface UIColor(Hex)
+ (UIColor *)hexColorWithString:(NSString *)string
NS_SWIFT_NAME(init(hexString:));
@end

// imports as
extension UIColor {
    init(hexString: String)
}

#1


15  

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.

编译器自动查找常见的ObjC命名模式,并在其位置替换Swift模式。一个ObjC类方法返回一个类的实例(并以某种方式命名,看起来像)被转换为Swift便利初始化器。

If you have the ObjC method (defined by a custom category):

如果您有ObjC方法(由自定义类别定义):

 + (UIColor *)colorWithHexString:(NSString *)hex alpha:(float)alpha;

The compiler generates the Swift declaration:

编译器生成Swift声明:

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. e.g.:

在Swift 2.0或更高版本中,您可以使用NS_SWIFT_NAME宏将ObjC工厂方法与作为初始化程序的Swift的命名模式导入不匹配。例如。:

@interface UIColor(Hex)
+ (UIColor *)hexColorWithString:(NSString *)string
NS_SWIFT_NAME(init(hexString:));
@end

// imports as
extension UIColor {
    init(hexString: String)
}