Swift: How to call a category or class method from Objective-C

大兔子大兔子 提交于 2020-01-03 17:20:31

问题


I have a category on UIImage that is written in Objective-C. The following are some example methods. How do I call these methods in Swift?

+(UIImage *) imageOrPDFNamed:(NSString *)resourceName; 
+(UIImage *) imageWithPDFNamed:(NSString *)resourceName;

I have tried the following and it does not recognize the methods:

let image = UIImage(imageOrPDFNamed:"test.pdf")
let image = UIImage(PDFNamed:"test.pdf")

回答1:


There are various cases for categories function and it's calling conventions.

1)In swift class functions in categories can be imported as convenience initializes if they returned same type on which they called like

 +(UIImage *) imageOrPDFNamed:(NSString *)resourceName ;

so it can be called as

    UIImage(orPDFNamed: "abc")

2)However if class functions in categories are not returning same object type(UIImage) on which it calls in this case UIImage like

   +(int) imageOrPDFNamedInt:(NSString *)resourceName ;

it will called as

    UIImage.imageOrPDFNamedInt("abc")

3)If categories function is not class function so it will call as directly on instance of UIImage like

   -(UIImage *) imagePDFNamed:(NSString *)resourceName ;

called as

    UIImage().imagePDFNamed("abc")



回答2:


This is finally what worked:

let image = UIImage(orPDFNamed:"test.pdf")


来源:https://stackoverflow.com/questions/25089142/swift-how-to-call-a-category-or-class-method-from-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!