首页 > 解决方案 > 将对象传递给 Swift 中的视图控制器

问题描述

如果Objective-C您需要将对象传递给 a ViewController,您可以执行以下操作:

在目标 .h 文件中

@property NSObject * contact;

在发送 .m 文件

MyVC *destVC = [self.storyboard instantiateViewControllerWithIdentifier:@"myVC"];
destVC.contact = contact;
[self.navigationController pushViewController:destVC animated:YES];

我正在尝试使用以下代码在 Swift 中执行此操作:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail")
//Following line causes error
//destVC.contact = latestContact
self.navigationController!.pushViewController(destVC, animated: true)

VC 启动正常,但是当我尝试将变量传递给它时,destVC.contact = latestContact编译器会说

类型的值ViewController没有这样的成员联系。

标签: iosswiftuiviewcontroller

解决方案


将其转换为您的子类视图控制器。说您的联系方式视图控制器类名称是ContactDetailsViewController

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if let destVC = storyBoard.instantiateViewController(withIdentifier: "contactDetail") as? ContactDetailsViewController {
   destVC.contact = latestContact
   self.navigationController!.pushViewController(destVC, animated: true)
}

推荐阅读