简体   繁体   English

在Objective-C中调用swift视图控制器文件的变量

[英]Calling to a variable of swift view controller file in Objective-C

I have a project that is a cross of Swift and Objective-C using a bridging-header. 我有一个使用网桥头的Swift和Objective-C交叉项目。

In my main ViewController.swift file, outside of the class declaration, I have this code: 在类声明之外的主ViewController.swift文件中,我有以下代码:

var mainView = ViewController()

In other views that I segue to, I can use this to call a function to run back on the main ViewController by using mainView.runFunction() 在我选择的其他视图中,我可以使用mainView.runFunction()来使用它来调用要在主ViewController上运行的函数

How can I call this function in an Objective-C .m implementation file? 如何在Objective-C .m实现文件中调用此函数?

Thanks! 谢谢!

First of all for using swift in objective-c you need to import TargetName-Swift.h . 首先,要在Objective-C中使用swift,您需要导入TargetName-Swift.h Note that it's the target name. 请注意,这是目标名称。

For more information look at this . 有关更多信息,请查看

You can achieve what you want in this way: 您可以通过这种方式实现您想要的:

ViewController *mainView = [[UIViewController alloc] init];
[mainView runFunction];

Also you should declare your runFunction with @objc to use it in objective-c like below: 另外,您应该使用@objc声明runFunction ,以便在Objective-c中使用它,如下所示:

@objc func runFunction {
    // what you want to do ...
}

Follow this apple article and done : Load Swift in Objective-C . 遵循这篇苹果文章并完成: 在Objective-C中加载Swift Or I already did is a "trick" using "@objc" key, look at this little explanation: What is @objc attribute , one easy way is just create a helper function that will be visible to your Objective-c class and done like: 或者我已经做过一个使用“ @objc”键的“技巧”,请看一下这个小解释: 什么是@objc属性 ,一种简单的方法是创建一个助手函数,该函数对于您的Objective-c类是可见的,就像:

@objc func retrieveMainView() -> UIViewController { return MyViewController() }

And you call this from your objective-c class, maybe you need to anotate your swift class with @objc, look at this two reference and you will get the idea and figure out for sure . 然后从Objective-C类中调用它,也许您需要使用@objc注释swift类,请看一下这两个引用,您将确定想法并确定。

In your Objective file ie .m file add below import statement: 在您的目标文件(即.m文件)中,添加以下导入语句:

import "<ProjectName>-Swift.h"

For example your project name is MyProject, so import statement would look like: 例如,您的项目名称为MyProject,因此import语句如下所示:

import "MyProject-Swift.h"

And call your function like: [mainView runFunction]; 并像这样调用您的函数: [mainView runFunction];

I hope this will help. 我希望这将有所帮助。 You can also refer one of my answer: How can I import Swift code to Objective-C? 您还可以参考我的答案之一: 如何将Swift代码导入到Objective-C?

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

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