ios - 将对象传递给 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
没有这样的成员联系。
解决方案
将其转换为您的子类视图控制器。说您的联系方式视图控制器类名称是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)
}
推荐阅读
- php - php debug_backtrace 在 CodeIgniter4 中找不到当前文件
- cmake - 如何使用组件创建 cmake 项目
- javascript - Javascript内存分配:堆和栈
- c++ - 为什么访问已删除的指针不会使程序崩溃?
- typescript - 如何检查两个属性是否同时为真或假
- javascript - 当页面上有很多项目时,Vuejs 似乎与 v-model 斗争
- javascript - 选择选项值未达到 if 语句
- python - 使用 web3.py 通过块哈希获取 Avalanche 块数据
- sql - 格式化 SQL 查询的输出
- google-apps-script - 从 Google AppScript 调用经过身份验证的云函数