如何在Swift中调用Objective-C类别方法 [英] How to call an Objective-C category method in Swift

查看:566
本文介绍了如何在Swift中调用Objective-C类别方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

编译器自动查找常见的ObjC命名模式和替代品快速模式取而代之。一个ObjC类方法返回一个类的实例(并以某种方式命名,看起来像)被转换为Swift便利初始化器。

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方法(由自定义类别定义):

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

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

编译器生成Swift声明:

The compiler generates the Swift declaration:

convenience init(hexString: String?, alpha: CFloat)

你这样称呼:

let color = UIColor(hexString: "#ffffff", alpha: 1.0)






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


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

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

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

这篇关于如何在Swift中调用Objective-C类别方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆