ios - 变量从另一个 swift 文件更改其值后返回 nil 值
问题描述
我正在尝试从另一个 Swift 文件中更改变量的值,但由于某种原因它不起作用并且返回 nil。
这是我尝试过的:
class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let si = self.storyboard?instantiateViewController(withIdentifier: "ShowIssueDetail") as! ShowIssueDetail
si.idSelected = indexPath.row //Here I change the value of the variable
performSegue(withIdentifier: "ShowIssueDetail", sender: self)
}
}
ShowIssueDetail.swift:
class ShowIssueDetail: UITableViewController {
var idSelected: Int! //This is the variable I want to change its value from the another swift file
override func viewDidLoad() {
print(idSelected) //Here it prints out nil instead of the selected row
}
}
我也以这种方式尝试过,但同样的问题:
class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let si = ShowIssueDetail()
si.idSelected = indexPath.row //Here I change the value of the variable
performSegue(withIdentifier: "ShowIssueDetail", sender: self)
}
}
我究竟做错了什么?
先感谢您!
注意:两个 swift 文件的类型不同,ShowIssues.swift 是 UIViewController,ShowIssueDetail 是 UITableViewController,我不知道它是否因此而不起作用。
解决方案
如果您在 Storyboard 中设置了 segue,则不应从代码中实例化目标视图控制器,Storyboard 将为您创建视图控制器。通过初始化另一个实例,您最终会在不会呈现给用户的实例上设置值。
您需要在prepare(for:)
那里覆盖并设置该值。
class ShowIssues: UIViewController, UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "ShowIssueDetail", sender: indexPath.row)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowIssueDetail", let destinationVC = segue.destination as? ShowIssueDetail, let selectedId = sender as? Int {
destinationVC.idSelected = selectedId
}
}
}
推荐阅读
- java - 父母的有效注释对孩子无效
- kotlin - 如何为 micronaut 中的所有控制器设置基本 URL?通过 application.yml 或任何配置
- python - 我的递归代码中的'Int object is not iterable error',不确定我哪里出错了
- php - 如何获取对 csv 文件的最后一次 fgetcsv 调用?
- c++ - 取消引用右值 shared_ptr
- node.js - 内存高效增长的 Nodejs Duplex/Transform 流
- javascript - 如何正确更新处于反应状态的对象或数组
- github - 从 PR 将 NuGet 包发布到 Azure Artifacts
- postgresql - 特性 `postgres::types::FromSql` 没有为 `bit_vec::BitVec` 实现
- ios - 分发失败,出现错误 iTunes 连接