简体   繁体   English

从 Objective-C 类调用 Swift 方法的语法

[英]Syntax to Call Swift Method from Objective-C Class

I am trying to call some code in a Utilities file written in swift from an objective-c file.我正在尝试从objective-c文件中调用以swift编写的Utilities文件中的一些代码。

Right now the class in the swift file looks like this:现在 swift 文件中的类如下所示:

class ImageClass: NSObject {
public func imageFromString(name: String?) -> UIImage? {
//code to make image

return image
}
}

I am trying to call it from the Objective-C file with:我试图从 Objective-C 文件中调用它:

 UIImage *myImage = [ImageClass imageFromString:@"test"];

however this is giving error:然而,这是给出错误:

Use of undeclared identifier 'ImageClass'

I know the Utilities file is reachable from the Objective-C file because I call other methods there though using a shared Instance.我知道 Utilities 文件可以从 Objective-C 文件访问,因为我使用共享实例调用了那里的其他方法。

Can anyone suggest the proper way to call the code?任何人都可以建议调用代码的正确方法吗? I actually don't care if it's a class or through a sharedInstance, I just need to be able to call it.我实际上不在乎它是一个类还是通过一个 sharedInstance,我只需要能够调用它。

Edit:编辑:

As suggested by @Charles Srstka, I CMD-clicked on the #import myapp.swift file, jumped to Definition, and it shows the following in the header:正如@Charles Srstka 所建议的那样,我 CMD 单击#import myapp.swift文件,跳转到定义,它在标题中显示以下内容:

- (UIImage * _Nullable)imageFromStringWithName:(NSString * _Nullable)name SWIFT_WARN_UNUSED_RESULT;

Accordingly, I tried adding WithName (which I'd forgotten) to the invocation so I have:因此,我尝试将 WithName (我忘记了)添加到调用中,所以我有:

 UIImage *myImage = [ImageClass imageFromStringWithName:@"test"];

but am still getting error with or without @objc before method:但是在使用或不使用 @objc before 方法时仍然出错:

No known class method for selector 'imageFromStringWithName:'

In swift 4.2 and latest在 swift 4.2 和最新版本中

  1. Add this line to your "*.m" file:将此行添加到您的“*.m”文件中:

     #import "YourProjectName-Swift.h"
  2. Add @objc before your function:在函数前添加@objc:

     @objc public func imageFromString(name: String?) -> UIImage? { //code to make the image return image }
  3. Call it inside Objective-C class:在 Objective-C 类中调用它:

     ImageClass *imgObject = [[ImageClass alloc] init]; UIImage *myImage = [imgObject imageFromStringWithName:@"test"];

Add this line to your Objective-C file:将此行添加到您的 Objective-C 文件中:

#import "YourProjectName-Swift.h"

Replace YourProjectName with the name of your project.YourProjectName替换为您的项目名称。 This will make all the Objective-C-compatible Swift classes in your project visible to your Objective-C code.这将使您的项目中所有与 Objective-C 兼容的 Swift 类对您的 Objective-C 代码可见。

Note that you'll also need to add the @objc annotation to your func declataions to make the methods visible to Objective-C.请注意,您还需要将@objc注释添加到您的func声明中,以使这些方法对 Objective-C 可见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM