将数据从Objective-C Viewcontroller传递到Swift ViewController

Isa*_*lle 3 objective-c uiviewcontroller swift

我试图将数据从Objective-C ViewController传递到Swift ViewController,并且在我的Objective-C控制器中遇到此错误:

在“ UIViewController”类型的对象上找不到属性“ type”

我的Objective-C代码:

UIViewController *mainController = [self.storyboard instantiateViewControllerWithIdentifier:@"IdentitySelfieViewController"];
mainController.type = "passport";
[self.navigationController pushViewController:mainController animated:YES];
Run Code Online (Sandbox Code Playgroud)

导入到桥接头文件中:

#import "PassportViewController.h"
Run Code Online (Sandbox Code Playgroud)

并在我的Swift View Controller中创建了相应的String

let type = ""
Run Code Online (Sandbox Code Playgroud)

感谢您的任何帮助

iOS*_*iOS 7

这是你的快速课程

步骤1:

class SwiftClassController: UIViewController {
//Required variables
@objc var deviceId: String?
@objc var deviceObj: CustomType?
Run Code Online (Sandbox Code Playgroud)

第2步:

在 Objective C 类中导入#import "YourProjectName-Swift.h"

步骤3:

在 Objective C 类中从 Swift 文件访问变量

YourViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"YourVC"];
vc.deviceId = @"1234567";
vc. deviceObj = yourCustomObject;
Run Code Online (Sandbox Code Playgroud)


Sha*_*jan 5

您的问题的解决方案是这样的:

首先在您的Swift Controller中@Objc,在class关键字之前添加如下代码:

@objc class ViewController: UIViewController
Run Code Online (Sandbox Code Playgroud)

然后在那个控制器中创建一个像这样的变量:

public var myValue:String  = ""
Run Code Online (Sandbox Code Playgroud)

之后,在Objective-CViewController中,您需要导入它,并记住这一点非常重要。

#import "TargetName-Swift.h"
Run Code Online (Sandbox Code Playgroud)

TargetName应替换为您的目标名称。之后,您可以像这样轻松地调用该Swift Controller的变量:

ViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"VC"];
vc.myValue = @"Hello";
Run Code Online (Sandbox Code Playgroud)

  • 就我的Swift4.2而言,我需要在变量声明之前添加@objc。例如:`@objc public var myValue:String =“”` (2认同)